﻿
Imports System.Data
Imports System.Data.SqlClient
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Imports Microsoft.VisualBasic

''' <summary>
''' 跟單-->約客
''' </summary>
''' <remarks>
''' <list>Create By:huyang </list>
''' <list>Create Date:2007-05-07</list>
''' <list>Function :約客</list>
''' </remarks>
Public Class Frm_OFSArrangeDelivery

    Implements IDServer.IDServer.IDServer
    Implements IContextMenuStrip

#Region "Variabled Define"

#Region "System Variabled Define"

    Public ActionHelp As IDServer.IDServer.ActionBtn = IDServer.IDServer.ActionBtn.ActionHelp

    Private WithEvents MainForm As Frm_MainForm

    Public Property SelectObject() As Frm_MainForm
        Get
            Return MainForm
        End Get
        Set(ByVal value As Frm_MainForm)
            MainForm = value
        End Set
    End Property

#End Region
    ''' <summary>
    ''' 填充訂單狀態
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub OrdeModeItem()
        Try
            Dim Dset As New DataSet
            Dim sql As String = ""
            sql &= "select ListA from BSC_OtherDefineB where ItemNo = 16 "
            Dset = Exec(sql, E_ExecType.DataSet)
            Me.cbx_Status.DataSource = Dset.Tables(0)
            Me.cbx_Status.DisplayMember = "ListA"


        Catch ex As Exception
            MessageBox.Show("Initialize:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK)
        End Try
    End Sub

#Region "User Variabled Define"

    ''' <summary>
    ''' 窗體是否已加載
    ''' </summary>
    ''' <remarks></remarks>
    Private fLoadBool As Boolean = False

    ''' <summary>
    ''' 倉庫表
    ''' </summary>
    ''' <remarks></remarks>
    Private StoreDtab As New DataTable

    ''' <summary>
    ''' 銷售定單表
    ''' </summary>
    ''' <remarks></remarks>
    Private SaleOrderDtab As New DataTable

    ''' <summary>
    ''' 是否可以勾選
    ''' </summary>
    ''' <remarks></remarks>
    Private fCheckBool As Boolean = False

    ''' <summary>
    ''' 定金比率
    ''' </summary>
    ''' <remarks></remarks>
    Private fPercentage As String = "25"

    ''' <summary>
    ''' 當前時間
    ''' </summary>
    ''' <remarks></remarks>
    Private fDateValue As Date

    ''' <summary>
    ''' 區域表
    ''' </summary>
    ''' <remarks></remarks>
    Private BSC_AreaSet As DataTable

    ''' <summary>
    ''' 車次表
    ''' </summary>
    ''' <remarks></remarks>
    Private Dtab_Truck As DataTable

    ''' <summary>
    ''' 明細界面
    ''' </summary>
    ''' <remarks></remarks>
    Private frmDestineCustDetail As Frm_OFSArrangeDeliveryDetail

    ''' <summary>
    ''' 操作步驟
    ''' </summary>
    ''' <remarks></remarks>
    Private Index As Integer = 1

    ''' <summary>
    ''' 是不是動態加載Tabpage 事件
    ''' </summary>
    ''' <remarks>
    ''' 用於記錄是否正在加載Tabpage True 正在加載 可以不用處理一些事件
    ''' False 已經加載完成
    ''' </remarks>
    Public AddTabBool As Boolean = False


#End Region

#Region "Const Define"

    Const ErrDateTime As String = "時間錄入錯誤！"
    Const ErrStartTimeOverEndTime As String = "開始時間不能大於結束時間"

#End Region

#End Region

#Region "Method Define"

#Region "Initilize"


    ''' <summary>
    ''' Initialize
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub Initialize()
        fDateValue = ServerDate
        Load_InitData()
        AddDestineDetail()
        setBtnEnabled()
        FillCombobox()
    End Sub

    ''' <summary>
    ''' 加載初始化數據集
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub Load_InitData()
        Try
            Dim Sql As String = ""
            Dim Dset As New DataSet

            ''倉庫
            ''Table[0]
            Sql &= " select Id,fCode,fShortName,fName from BSC_StoreHouse " & vbCrLf

            ''銷售定單
            ''Table[1]
            Sql &= " select ID,fSaleOrdeNo,fWriteNo,fDeliverMode,fCustomerId,(select Cnname from dbo.BSC_Customer b where Isnull(a.fCustomerId,'')=Isnull(b.id,'')) as Cnname," & vbCrLf
            Sql &= " ShopNo,(select fShortName from BSC_StoreHouse d where Isnull(a.ShopNo,'')=Isnull(d.fCode,'')) as fShortName,fEmployeeId,(select fCName from BSC_Employee c where Isnull(a.fEmployeeId,'')=Isnull(c.fCode,'')) as fEmployeeName,fSaleDate,fOperaterMan," & vbCrLf
            Sql &= " fOperateDate,fOrdeStatus,fStoreCode,fDSIA,fDSIB,fBSI,FTAmount,fPayMode,fRemark,convert(varchar(10),fBuiltDate,21) as fBuildDate,Left(Replace(fSaleDate,'-',''),6) as fDateKey " & vbCrLf
            Sql &= " from Sal_SaleOrdeA a where 1<>1  order by fSaleDate asc   " & vbCrLf

            ''定金比率
            ''Table[2]
            Sql &= " select * from dbo.BSC_OtherDefineB where ItemNo=67 " & vbCrLf

            ''區域表
            ''Table[3]
            Sql &= " select * from BSC_AreaSet order by AreaNum " & vbCrLf

            ''具體車次
            ''Table[4]
            Sql &= " select * from BSC_Truck " & vbCrLf

            Dset = App.ReturnDataset(Sql)

            Me.StoreDtab = Dset.Tables(0).Copy

            SaleOrderDtab = Dset.Tables(1).Copy

            BSC_AreaSet = Dset.Tables(3).Copy

            Dtab_Truck = Dset.Tables(4).Copy

            If Dset.Tables(2).Rows.Count > 0 Then
                fPercentage = Dset.Tables(2).Rows(0).Item("ListCode")
            End If

        Catch ex As Exception
            MessageBox.Show("Load_InitData:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 返回網格列標頭
    ''' </summary>
    ''' <param name="Index"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function Re_CaptionHash(ByVal Index As Integer) As Hashtable
        Dim Hash As New Hashtable
        Try

            With Hash
                Select Case Index
                    Case 1

                        .Add("fDeliverId", "排程單號")
                        .Add("AreaName", "路線")
                        .Add("fDeliverDate", "送貨日期")
                        .Add("TruckName", "車名")
                        .Add("Status", "狀態")
                        .Add("Remark", "備注")
                        .Add("BuildDate", "建檔日期")
                        .Add("BuildPsn", "建檔者")
                        .Add("BuildComputer", "建檔電腦")
                        .Add("UpdateDate", "更新日期")
                        .Add("UpdatePsn", "更新者")
                        .Add("UpdateComputer", "更新電腦")

                    Case 2
                        .Add("CheckA", "選擇")
                        .Add("fSaleOrdeNo", "銷售單號")
                        .Add("fCustomerId", "客戶編號")
                        .Add("fWriteNo", "手寫單號")
                        .Add("fCustomerName", "客戶名稱")
                        .Add("fSaleDate", "合同日期")
                        .Add("SiteNo", "站點")
                        '.Add("fDeliverDate", "送貨日期")
                        .Add("fAecceptDate", "時間")

                        .Add("fTelphone", "電話")
                        .Add("fConsigneeMan", "收貨人")
                        .Add("fAddressName", "送貨地址")
                        .Add("fEmployeeId", "銷售人員")
                        .Add("fDSIA", "即付定金")
                        .Add("fDSIB", "共收定金")
                        .Add("fBSI", "尾數")
                        .Add("fPayMode", "付款模式")

                        '.Add("OutStoreHouse", "出貨點")
                        .Add("Ticket", "是否開票")

                        .Add("fRemark", "備注")
                        .Add("DeliverRemark", "安裝備注")
                        .Add("FNum", "尾數發票")
                        .Add("BillStatus", "狀態")


                    Case 3

                        .Add("CheckA", "選擇")
                        '.Add("ItemNo", "編號")
                        .Add("fGoodsBarCode", "貨品條碼")
                        .Add("SupperItem", "產商編碼")
                        .Add("Enname", "英文名稱")
                        .Add("GoodsName", "貨品名稱")
                        .Add("ColorSName", "貨品顏色")
                        .Add("SizeSName", "貨品規格")
                        .Add("fGoodsamount", "數量")
                        .Add("GoodsPrice", "銷售價")
                        .Add("fSumMoney", "總金額")
                        .Add("fHouseId", "出貨點")
                        .Add("fRemark", "備註")

                End Select
            End With

        Catch ex As Exception
            MessageBox.Show("Re_CaptionHash:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
        Return Hash
    End Function

    ''' <summary>
    ''' 添加明細窗體
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub AddDestineDetail()
        Try

            frmDestineCustDetail = New Frm_OFSArrangeDeliveryDetail
            Me.frmDestineCustDetail.Dock = DockStyle.Fill
            frmDestineCustDetail.Set_BSC_AreaSetDtab = Me.BSC_AreaSet
            frmDestineCustDetail.Set_fPercentage = fPercentage
            frmDestineCustDetail.Set_btnPrevious = Me.btnPrevious
            frmDestineCustDetail.Set_btnNext = Me.btnNext
            frmDestineCustDetail.Set_Dtab_Truck = Me.Dtab_Truck
            Me.Panel_Main.Controls.Add(frmDestineCustDetail)
            Me.Panel_Main.CreateControl()

        Catch ex As Exception
            MessageBox.Show("AddDestineDetail:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK)
        End Try
    End Sub

    ''' <summary>
    ''' 填充下拉
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub FillCombobox()
        Try
            Dim Dtab As DataTable = Me.BSC_AreaSet.Copy
            Me.cbx_fCarNo.DataSource = Dtab

            Me.cbx_fCarNo.DisplayMember = "AreaName"
            Me.cbx_fCarNo.ValueMember = "AreaCode"
            Me.cbxfCarNo.DataSource = Dtab
            Me.cbxfCarNo.DisplayMember = "AreaName"
            Me.cbxfCarNo.ValueMember = "AreaCode"

            Dtab.DefaultView.RowFilter = "ParentId=0"
            cbxfCarNo.Text = ""
        Catch ex As Exception
            MessageBox.Show("FillCombobox:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 返回可編輯的列
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function Re_EnabledColumnEdit() As Hashtable
        Dim Hash As New Hashtable
        Try

            With Hash
                .Add("SiteNo", "SiteNo")
                '.Add("fAecceptDate1", "fAecceptDate1")
                '.Add("fAecceptDate2", "fAecceptDate2")
                '.Add("fTelphone", "fTelphone")
                '.Add("fConsigneeMan", "fConsigneeMan")
                '.Add("fAddressName", "fAddressName")
                '.Add("fRemark", "fRemark")
            End With

        Catch ex As Exception
            MessageBox.Show("Re_EnabledColumnEdit:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
        Return Hash
    End Function

#End Region

#Region "TreeView Mehtod"

    ''' <summary>
    ''' 加載樹
    ''' </summary>
    ''' <param name="Tvw"></param>
    ''' <param name="titleText"></param>
    ''' <param name="CheckBool"></param>
    ''' <remarks></remarks>
    Private Sub Load_TreeView(ByRef Tvw As TreeView, ByVal titleText As String, Optional ByVal CheckBool As Boolean = False)
        Try

            Tvw.Nodes.Clear()

            Dim Node As TreeNode = Tvw.Nodes.Add("0", titleText)
            Node.Tag = "0"
            If CheckBool = True Then
                Tvw.CheckBoxes = True
            End If
            Node.Nodes.Add("...")
            Node.Expand()
            Tvw.SelectedNode = Node

            Me.LoadNodeImage(Node, 0)

        Catch ex As Exception
            MessageBox.Show("Load_TreeView:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 加載圖片
    ''' </summary>
    ''' <param name="Node"></param>
    ''' <param name="Level"></param>
    ''' <remarks></remarks>
    Private Sub LoadNodeImage(ByVal Node As TreeNode, ByVal Level As Integer)
        Select Case Level
            Case 0
                Node.ImageIndex = 1
                Node.SelectedImageIndex = 2
            Case 1
                Node.ImageIndex = 1
                Node.SelectedImageIndex = 2
            Case 2
                Node.ImageIndex = 1
                Node.SelectedImageIndex = 2
            Case 3
                Node.ImageIndex = 1
                Node.SelectedImageIndex = 2
            Case 4
                Node.ImageIndex = 1
                Node.SelectedImageIndex = 2
            Case Else
                Node.ImageIndex = 1
                Node.SelectedImageIndex = 2
        End Select
    End Sub

    ''' <summary>
    ''' 加載樹結點
    ''' </summary>
    ''' <param name="Node"></param>
    ''' <remarks></remarks>
    Private Sub Load_TreeNode(ByRef Node As TreeNode)
        Try

            ''結點已加載退出
            If Node.Nodes.Count > 1 OrElse Node.Nodes(0).Text.Trim <> "...".Trim Then Exit Sub

            Node.Nodes.Clear()

            Select Case Node.Level

                Case 0 ''加載公司

                    For Each Row As DataRow In Me.StoreDtab.Rows
                        Dim NodeKey As String = Row("fCode") & ""
                        Dim NodeText As String = Row("fShortName") & "[" & NodeKey & "]"
                        Dim Tnode As TreeNode = Node.Nodes.Add(NodeKey, NodeText)
                        Tnode.Tag = NodeKey
                        Me.LoadNodeImage(Tnode, 1)
                        If SaleOrderDtab.Select("Isnull(fShopNo,'')='" & NodeKey & "'").Length > 0 Then
                            Tnode.Nodes.Add("...")
                        End If
                    Next

                Case 1   ''加載年月

                    Dim fCode As String = Node.Tag.ToString.Split(":")(0).Trim
                    Dim DRow() As DataRow = Me.SaleOrderDtab.Select("Isnull(fShopNo,'')='" & fCode & "'", "fSaleDate asc")
                    Dim Dic As New System.Collections.Specialized.StringDictionary

                    For Each Row As DataRow In DRow
                        Dim fDateKey As String = Row("fDateKey").ToString.Trim & ""
                        If Dic.ContainsKey(fDateKey) = False Then
                            Dic.Add(fDateKey, fDateKey)
                            Dim NodeKey As String = fCode & ":" & fDateKey
                            Dim NodeText As String = fDateKey
                            Dim Tnode As TreeNode = Node.Nodes.Add(NodeKey, NodeText)
                            Tnode.Tag = NodeKey
                            Me.LoadNodeImage(Tnode, 2)
                            Tnode.Nodes.Add("...")
                        End If
                    Next

                Case 2
                    Dim fCode As String = Node.Tag.ToString.Split(":")(0).Trim
                    Dim fDateKey As String = Node.Tag.ToString.Split(":")(1).Trim

                    Dim DRow() As DataRow = Me.SaleOrderDtab.Select("Isnull(fShopNo,'')='" & fCode & "' and Isnull(fDateKey,'')='" & fDateKey & "'", "fSaleDate asc")
                    For Each Row As DataRow In DRow

                        Dim fSaleOrdeNo As String = Row("fSaleOrdeNo").ToString.Trim & ""
                        Dim NodeKey As String = Node.Tag.ToString.Trim & ":" & fSaleOrdeNo
                        Dim NodeText As String = fSaleOrdeNo

                        Dim Tnode As TreeNode = Node.Nodes.Add(NodeKey, NodeText)
                        Tnode.Tag = NodeKey
                        Me.LoadNodeImage(Tnode, 3)
                    Next
                Case 3

                Case 4

                Case Else


            End Select

        Catch ex As Exception
            MessageBox.Show("Load_TreeNode:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

#End Region

#Region "ExecFind"

    ''' <summary>
    ''' 返回查詢條件
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function Re_WhereExp() As String
        Dim Sql As String = ""
        Try
            If Me.fLoadBool = False Then
                Sql &= "  where 1<>1 "
            Else
                Sql &= "  where 1=1 "

                If Me.txt_fDeliverId.Text.Trim <> "" Then
                    Sql &= "  and a.fDeliverId like '%" & Replace_Text(Me.txt_fDeliverId.Text.Trim) & "%'"
                End If
                If Me.txt_fSaleOrdeNo.Text.Trim <> "" Then
                    Sql &= "  and b.fSaleOrdeNo like '%" & Replace_Text(Me.txt_fSaleOrdeNo.Text.Trim) & "%'"
                End If
                If Me.cbx_fCarNo.Text.Trim <> "" Then
                    If Not Me.cbx_fCarNo.SelectedValue Is Nothing Then
                        Sql &= "  and a.fCarNo='" & Me.cbx_fCarNo.SelectedValue & "'"
                    End If
                End If
                If IsDate(Me.dtp_StartDate.Text.Trim) = True Then
                    Sql &= "  and  Convert(varchar(10),a.fDeliverDate,21)>='" & Me.dtp_StartDate.Text.Trim & "'"
                End If
                If IsDate(Me.dtp_EndDate.Text.Trim) = True Then
                    Sql &= "  and  Convert(varchar(10),a.fDeliverDate,21)<='" & Me.dtp_EndDate.Text.Trim & "'"
                End If
                If Me.cbx_Status.Text.Trim <> "" Then
                    Sql &= "  and  C.ListA like '%" & Replace_Text(Me.cbx_Status.Text.Trim) & "%'"
                End If

            End If
        Catch ex As Exception
            MessageBox.Show("Re_WhereExp:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
        Return Sql
    End Function

    ''' <summary>
    ''' 查詢
    ''' </summary>
    ''' <param name="WhereExp"></param>
    ''' <remarks></remarks>
    Private Sub ExecFind(ByVal WhereExp As String)
        Try
            Me.Cursor = Cursors.WaitCursor
            Dim Sql As String = ""
            Dim Dtab As New DataTable

            If Validated_ExecFind() = False Then Exit Sub

            Sql &= " select distinct a.Id,a.fDeliverId,fCarNo,fCarName as AreaName ,fTructCode,fTruckName as TruckName,Convert(varchar(10),fDeliverDate,21) as fDeliverDate,fEmployeeId,(select Top 1 ListA from BSC_OtherDefineB c where c.ItemNo=16 and Isnull(a.Status,'A')=Isnull(c.ListCode,'A')) AS Status,Status as fStatus,Remark," & vbCrLf
            Sql &= " Convert(varchar(10),BuildDate,21) as BuildDate,BuildPsn,BuildComputer,Convert(varchar(10),UpdateDate,21) as UpdateDate,UpdatePsn,UpdateComputer,fCheckMan,Convert(varchar(10),fCheckDate,21) as fCheckDate,fCheckComputer,fUnCheckMan,Convert(varchar(10),fUnCheckDate,21) as fUnCheckDate,fUnCheckComputer from DeliverGoodsMaster  a left join BSC_OtherDefineB c on a.Status = c.ListCode  inner join  dbo.DeliverGoodsDetail  b on a.fDeliverId=b.fDeliverId   " & WhereExp & vbCrLf

            Dtab = Exec(Sql, E_ExecType.DataTable)

            Me.DGView_1_1.DataSource = Dtab
            BindDataGridViewCaption(Me.DGView_1_1, Me.Re_CaptionHash(1))

            If Me.fLoadBool = True Then
                SetButton(ButtonType.Browse, True)
            Else
                Me.btnPrintInv.Enabled = False
            End If
            SetDataGridViewBackColor(Me.DGView_1_1, "Status")



        Catch ex As Exception
            MessageBox.Show("ExecFind:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub

#End Region

#Region "Fill Detail"

    ''' <summary>
    ''' 填充DGV_2_1網格
    ''' </summary>
    ''' <param name="fDeliverId"></param>
    ''' <remarks></remarks>
    Private Sub FillDataGrid(Optional ByVal fDeliverId As String = "")
        Try
            Dim Sql As String = " "

            Dim Dset As New DataSet

            Dim WhereExp As String = " where Isnull(a.fDeliverId,'')='" & fDeliverId & "'" & vbCrLf

            Sql = Re_DeliverGoodsSaleSql(WhereExp)

            Dset = Exec(Sql, E_ExecType.DataSet)

            Dim DetailDtab As DataTable = DirectCast(Me.DGView_2_2.DataSource, DataTable)
            If Not DetailDtab Is Nothing Then
                DetailDtab.Clear()
                DetailDtab.AcceptChanges()
            End If

            Me.DGView_2_1.DataSource = Dset.Tables(0)
            BindDataGridViewCaption(Me.DGView_2_1, Me.Re_CaptionHash(2))
            If Me.DGView_2_1.Columns.Count > 0 Then
                If Me.DGView_2_1.Columns.Contains("fRemark") Then
                    Me.DGView_2_1.Columns("fRemark").Width = 300
                End If
                If Me.DGView_2_1.Columns.Contains("DeliverRemark") Then
                    Me.DGView_2_1.Columns("DeliverRemark").Width = 300
                End If
            End If

            DGView_2_1.MultiSelect = True

        Catch ex As Exception
            MessageBox.Show("FillDataGrid_3_1:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 填充網格DGView_2_2
    ''' </summary>
    ''' <param name="fDeliverId">送貨單號</param>
    ''' <param name="fSaleOrdeNo">銷售定單</param>
    ''' <remarks></remarks>
    Private Sub FillDetailGrid(Optional ByVal fDeliverId As String = "", Optional ByVal fSaleOrdeNo As String = "")
        Try
            Dim Sql As String = ""

            Sql &= Re_DeliverGoodsDetailInfo(fDeliverId, fSaleOrdeNo)

            Dim Dtab As New DataTable
            Dtab = Exec(Sql, E_ExecType.DataTable)

            Me.DGView_2_2.DataSource = Dtab
            BindDataGridViewCaption(Me.DGView_2_2, Me.Re_CaptionHash(3))
            DGView_2_2.Columns("fGoodsamount").DefaultCellStyle.Format = "0.00"
            DGView_2_2.Columns("fSumMoney").DefaultCellStyle.Format = "0.00"
            DGView_2_2.SelectionMode = DataGridViewSelectionMode.CellSelect
            DGView_2_2.Columns("fRemark").DefaultCellStyle.ForeColor = Color.Blue
            DGView_2_2.Columns("fRemark").Width = 100
        Catch ex As Exception
            MessageBox.Show("FillDetailGrid:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    'Public Sub FullFormatDataGridView(ByRef DGView As DataGridView, Optional ByVal addBool As Boolean = False, Optional ByVal deleteBool As Boolean = False, _
    '  Optional ByVal editBool As Boolean = False, Optional ByVal autoSizeBool As Boolean = True, Optional ByVal RowHeadersVisible As Boolean = True)
    '    Try
    '        With DGView
    '            .AllowUserToAddRows = addBool
    '            .AllowUserToDeleteRows = deleteBool
    '            .AutoSize = True
    '            .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None
    '            .AllowUserToResizeColumns = True
    '            .AllowUserToResizeRows = True
    '            .AllowUserToOrderColumns = True
    '            '.AutoResizeColumns()
    '            .GridColor = Color.Gainsboro
    '            .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter
    '            '.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells
    '            ''.CellBorderStyle = DataGridViewCellBorderStyle.
    '            .ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single
    '            .ReadOnly = Not (addBool OrElse editBool OrElse deleteBool)
    '            If addBool = True OrElse editBool = True Then
    '                .SelectionMode = DataGridViewSelectionMode.RowHeaderSelect
    '            Else
    '                .SelectionMode = DataGridViewSelectionMode.FullRowSelect
    '            End If
    '            .MultiSelect = False
    '            .RowHeadersVisible = RowHeadersVisible

    '            DGView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders
    '            DGView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None
    '            DGView.RowsDefaultCellStyle.WrapMode = DataGridViewTriState.True
    '            DGView.Update()

    '            '.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(221, 221, 221)

    '            '.AutoResizeColumns()

    '        End With
    '    Catch ex As Exception
    '        MsgBox("FormatDataGridView:" & ex.Message & ex.StackTrace, MsgBoxStyle.Critical And MsgBoxStyle.OkOnly, Msg.CompanyName)
    '    End Try
    'End Sub

    ''' <summary>
    ''' 填充明細
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub FillDetail()
        Try
            Dim fDeliverId As String = ""

            If Not Me.DGView_1_1.CurrentRow Is Nothing Then
                fDeliverId = Me.DGView_1_1.CurrentRow.Cells("fDeliverId").Value & ""
            End If

            Dim Dtab As DataTable = DirectCast(Me.DGView_1_1.DataSource, DataTable)
            Dim DRow() As DataRow = Dtab.Select("Isnull(fDeliverId,'')='" & fDeliverId & "'")
            If DRow.Length > 0 Then

                Me.txtfDeliverId.Text = DRow(0).Item("fDeliverId") & ""
                Me.cbxfCarNo.Text = DRow(0).Item("AreaName") & ""
                Me.mtbfDeliverDate.Text = DRow(0).Item("fDeliverDate") & ""
                Me.txtfTruckName.Text = DRow(0).Item("TruckName") & ""
                Me.lbBuildDate.Text = DRow(0).Item("BuildDate") & ""
                Me.lbBuildPsn.Text = DRow(0).Item("BuildPsn") & ""
                Me.lbUpdateDate.Text = DRow(0).Item("UpdateDate") & ""
                Me.lbUpdatePsn.Text = DRow(0).Item("UpdatePsn") & ""
                Me.lbStatus.Text = DRow(0).Item("Status") & ""

            Else

                Me.txtfDeliverId.Text = ""
                Me.cbxfCarNo.Text = ""
                Me.mtbfDeliverDate.Text = ""
                Me.txtfTruckName.Text = ""
                Me.lbBuildDate.Text = ""
                Me.lbBuildPsn.Text = ""
                Me.lbUpdateDate.Text = ""
                Me.lbUpdatePsn.Text = ""
                Me.lbStatus.Text = ""

            End If

            FillDataGrid(fDeliverId)

        Catch ex As Exception
            MessageBox.Show("FillDetail:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

#End Region

#Region "Control Method"

    ''' <summary>
    ''' 設置按鈕狀態
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub setBtnEnabled()
        Try
            Select Case Index
                Case 1
                    Me.btnPrevious.Enabled = False
                    Me.btnNext.Enabled = True
                    Me.btnNext.Text = "下一步"
                Case 2
                    Me.btnPrevious.Enabled = True
                    Me.btnNext.Enabled = True
                    Me.btnNext.Text = "下一步"
                Case 3
                    Me.btnPrevious.Enabled = True
                    Me.btnNext.Enabled = False
                    Me.btnNext.Text = "完成"
                Case 4
                    Me.btnPrevious.Enabled = False
                    Me.btnNext.Enabled = False
                    Me.btnNext.Text = "完成"
                Case Else
                    Me.btnPrevious.Enabled = True
                    Me.btnNext.Enabled = False
            End Select
        Catch ex As Exception
            MessageBox.Show("setBtnEnabled:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK)
        End Try
    End Sub

    ''' <summary>
    ''' 動態加載頁面
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub AddTabpage()

        Dim TabName As String = "TabPage" & Index.ToString
        Me.frmDestineCustDetail.DynamicAddTabpage(TabName)


    End Sub


#End Region

#Region "操作步驟"

    ''' <summary>
    ''' 操作步驟
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub SetpOperate()
        Try
            Select Case Index
                Case 1

                Case 2
                    StepOperateSecord()
                Case 3
                    SetpOperateThree()
                Case 4

                Case Else

            End Select
        Catch ex As Exception
            MessageBox.Show("SetpOperate:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub


    ''' <summary>
    ''' 第二步
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub StepOperateSecord()
        Try

            Dim Dset As New DataSet
            Dim Sql As String = ""
            Dim WhereExp1 As String = ""

            Select Case Me.frmDestineCustDetail.cbxfDestineStatus.Text

                Case E_DestineStatus.已排.ToString, E_DestineStatus.未排.ToString, E_DestineStatus.未選定.ToString

                    'Sql &= "    select * from (" & vbCrLf
                    'Sql &= "    select  Isnull(c.fDeliverId,'') as fDeliverId,a.Id,a.fSaleOrdeNo,fWriteNo," & vbCrLf
                    'Sql &= "    (select Top 1 ListA from BSC_OtherDefineB where ItemNo=(" & vbCrLf
                    'Sql &= "    select Top 1 Id from dbo.BSC_OtherDefineA where ItemCode='SaleType'" & vbCrLf
                    'Sql &= "    ) and ListCode=a.fDeliverMode) as fDeliverMode," & vbCrLf
                    'Sql &= "    a.fDeliverDate, fCustomerId, " & vbCrLf
                    'Sql &= "    a.fCustomerName as Cnname,a.fDeliverAddress,a.fLinkPhone as Telphone,fLinkMan as LinkMan," & vbCrLf
                    'Sql &= "    fAreaId,ShopNo,(select fShortName from BSC_StoreHouse d where Isnull(a.ShopNo,'')=Isnull(d.fCode,'')) as fShortName," & vbCrLf
                    'Sql &= "    a.fEmployeeId,(select fCName from BSC_Employee c where Isnull(a.fEmployeeId,'')=Isnull(c.fCode,'')) as fEmployeeName,fSaleDate,fOperaterMan,fOperateDate,fStoreCode," & vbCrLf
                    'Sql &= "    fDSIA,fDSIB,fBSI,fPayMode,a.fRemark,fBuiltDate as fBulidDate,c.fDeliverDate as fDestineDate,case when Isnull(c.fDeliverDate,'')='' then a.fDeliverDate else c.fDeliverDate end  as fDateKey," & vbCrLf
                    'Sql &= "    dbo.GetParentId(fAreaId) as fAreaId01,fAreaId as fAreaId02,a.fOrdeStatus,a.fGoodsType, " & vbCrLf
                    'Sql &= "    (select Top 1 TruckName from BSC_Truck  d where d.TruckId=c.fTructCode) as TruckName " & vbCrLf
                    'Sql &= "    from Sal_SaleOrdeA a " & vbCrLf

                    'Sql &= "    left join V_DeliverGoods c on (a.fSaleOrdeNo=c.fSaleOrdeNo) ) a " & WhereExp1 & vbCrLf & vbCrLf


                    ''加快查詢速度

                    Dim whereExpV2 As String = ReturnWhere_2(2)

                    Sql &= " select * from (" & vbCrLf
                    Sql &= " select Isnull(c.fDeliverId,'') as fDeliverId,a.Id,a.fSaleOrdeNo,a.fWriteNo,b.ListA as fDeliverMode," & vbCrLf
                    Sql &= " a.fDeliverDate, fCustomerId," & vbCrLf
                    Sql &= " a.fCustomerName as Cnname,a.fDeliverAddress,a.fLinkPhone as Telphone,fLinkMan as LinkMan," & vbCrLf
                    Sql &= " fAreaId=case when Isnull(fAreaCode,'')='' then fAreaId else fAreaCode end,a.ShopNo,e.fShortName," & vbCrLf
                    Sql &= " a.fEmployeeId,f.fCName as fEmployeeName," & vbCrLf
                    Sql &= " fSaleDate,fOperaterMan,fOperateDate,fStoreCode," & vbCrLf
                    Sql &= "  isnull (n.fDSIA,'0.00') as fDSIA,isnull (n.fDSIB,'0.00') as fDSIB,isnull (n.fBSI,'0.00') as fBSI, isnull (a.fTAmount,'0.00') as fTAmount,fPayMode,a.fRemark,fBuiltDate as fBulidDate,c.fDeliverDate as fDestineDate,case when Isnull(c.fDeliverDate,'')='' then a.fDeliverDate else c.fDeliverDate end  as fDateKey," & vbCrLf

                    Sql &= " fAreaId01=Isnull(d.ParentId,'')," & vbCrLf
                    Sql &= " case when Isnull(fAreaCode,'')='' then fAreaId else fAreaCode end as fAreaId02,a.fOrdeStatus,a.fGoodsType," & vbCrLf
                    Sql &= " TruckName" & vbCrLf
                    Sql &= " from Sal_SaleOrdeA a" & vbCrLf
                    Sql &= " left join  V_DeliverGoods c on (a.fSaleOrdeNo=c.fSaleOrdeNo) " & vbCrLf
                    Sql &= " left join  BSC_AreaSet d on (convert(nvarchar(50),d.Id)=Isnull(fAreaId,''))" & vbCrLf
                    Sql &= " left join  V_BSC_OtherDefine b on (b.ListCode=a.fDeliverMode)" & vbCrLf
                    Sql &= " left join  BSC_StoreHouse e on (Isnull(a.ShopNo,'')=Isnull(e.fCode,''))" & vbCrLf
                    Sql &= " left join  BSC_Employee f on (Isnull(a.fEmployeeId,'')=Isnull(f.fCode,''))" & vbCrLf
                    Sql &= " left join  BSC_Truck g on (g.TruckId=c.fTructCode)" & vbCrLf
                    Sql &= " left join (select * from Sal_InvoiceA where FType='DEPOSIT')n ON a.fSaleOrdeNo = n.FSaleOrdeNo" & vbCrLf
                    Sql &= " where Isnull(fDeliverMode,'')='S2'" & vbCrLf
                    Sql &= " and Isnull(fOrdeStatus,'A')='B' " & vbCrLf
                    Sql &= ")  a" & vbCrLf
                    Sql &= " " & whereExpV2 & vbCrLf
                    Sql &= " order by fSaleDate" & vbCrLf


                Case Else

                    'WhereExp1 = Me.Re_WhereExp_Step(2)
                    'Dim WhereExp3 As String = Me.Re_WhereExp_Step(4)


                    'Dim TabA As String = System.Guid.NewGuid().ToString
                    'Dim TabB As String = System.Guid.NewGuid().ToString
                    'Dim TabC As String = System.Guid.NewGuid().ToString

                    'Sql &= "    select *  Into [#" & TabA & "] from (" & vbCrLf
                    'Sql &= "    select  Isnull(c.fDeliverId,'') as fDeliverId,a.Id,a.fSaleOrdeNo,fWriteNo," & vbCrLf
                    'Sql &= "    (select Top 1 ListA from BSC_OtherDefineB where ItemNo=(" & vbCrLf
                    'Sql &= "    select Top 1 Id from dbo.BSC_OtherDefineA where ItemCode='SaleType'" & vbCrLf
                    'Sql &= "    ) and ListCode=a.fDeliverMode) as fDeliverMode," & vbCrLf
                    'Sql &= "    a.fDeliverDate, fCustomerId, " & vbCrLf
                    'Sql &= "    a.fCustomerName as Cnname,a.fDeliverAddress,a.fLinkPhone as Telphone,fLinkMan as LinkMan," & vbCrLf
                    'Sql &= "    fAreaId,ShopNo,(select fShortName from BSC_StoreHouse d where Isnull(a.ShopNo,'')=Isnull(d.fCode,'')) as fShortName," & vbCrLf
                    'Sql &= "    a.fEmployeeId,(select fCName from BSC_Employee c where Isnull(a.fEmployeeId,'')=Isnull(c.fCode,'')) as fEmployeeName,fSaleDate,fOperaterMan,fOperateDate,fStoreCode," & vbCrLf
                    'Sql &= "    fDSIA,fDSIB,fBSI,fPayMode,a.fRemark,fBuiltDate as fBulidDate,Isnull(c.fDeliverDate,'') as fDestineDate,case when Isnull(c.fDeliverDate,'')='' then a.fDeliverDate else c.fDeliverDate end  as fDateKey," & vbCrLf
                    'Sql &= "    dbo.GetParentId(fAreaId) as fAreaId01,Isnull(fAreaId,'') as fAreaId02,a.fOrdeStatus,a.fGoodsType, " & vbCrLf
                    'Sql &= "    (select Top 1 TruckName from BSC_Truck  d where d.TruckId=c.fTructCode) as TruckName " & vbCrLf
                    'Sql &= "    from Sal_SaleOrdeA a " & vbCrLf

                    'Sql &= "    left join V_DeliverGoods c on (a.fSaleOrdeNo=c.fSaleOrdeNo) ) a " & WhereExp1 & vbCrLf & vbCrLf



                    'Sql &= "    select a.fSaleOrdeNo,b.ItemNo,Isnull(Sum(b.fTotal),0) as fTotal into[#" & TabB & "] from dbo.DeliverGoodsDetail a" & vbCrLf
                    'Sql &= "    inner join DeliverGoodsInfo b on a.fDeliverId=b.fDeliverId and a.fSaleOrdeNo=b.fSaleOrdeNo" & vbCrLf
                    'Sql &= "    where Isnull(fSplitStatus,0)=1 group by a.fSaleOrdeNo,b.ItemNo" & vbCrLf


                    'Sql &= "    select a.fSaleOrdeNo,a.ItemNo,a.fSumCount-Isnull(c.fTotal,0) as fSumCount Into[#" & TabC & "] from dbo.Sal_SaleOrdeB a " & vbCrLf
                    'Sql &= "    inner join dbo.Sal_SaleOrdeA b on a.fSaleOrdeNo=b.fSaleOrdeNo" & vbCrLf
                    'Sql &= "    left join [#" & TabB & "] c on a.fSaleOrdeNo=b.fSaleOrdeNo and a.ItemNo=c.ItemNo" & vbCrLf
                    'Sql &= "    " & WhereExp3 & "  and  (a.fSumCount-Isnull(c.fTotal,0))>0 and a.fSaleOrdeNo in (select fSaleOrdeNo from [#" & TabB & "])" & vbCrLf

                    'Sql &= "    select * from [#" & TabA & "] a " & vbCrLf
                    'Sql &= "    union" & vbCrLf
                    'Sql &= "    select Convert(varchar(50),'') as fDeliverId,a.Id,a.fSaleOrdeNo,fWriteNo," & vbCrLf
                    'Sql &= "    (select Top 1 ListA from BSC_OtherDefineB where ItemNo=(" & vbCrLf
                    'Sql &= "    select Top 1 Id from dbo.BSC_OtherDefineA where ItemCode='SaleType'" & vbCrLf
                    'Sql &= "    ) and ListCode=a.fDeliverMode) as fDeliverMode," & vbCrLf
                    'Sql &= "    a.fDeliverDate,fCustomerId,a.fCustomerName as Cnname,a.fDeliverAddress,a.fLinkPhone as Telphone,fLinkMan as LinkMan," & vbCrLf
                    'Sql &= "    fAreaId,ShopNo,(select fShortName from BSC_StoreHouse d where Isnull(a.ShopNo,'')=Isnull(d.fCode,'')) as fShortName," & vbCrLf
                    'Sql &= "    a.fEmployeeId,(select fCName from BSC_Employee c where Isnull(a.fEmployeeId,'')=Isnull(c.fCode,'')) as fEmployeeName,fSaleDate,fOperaterMan,fOperateDate,fStoreCode," & vbCrLf
                    'Sql &= "    fDSIA,fDSIB,fBSI,fPayMode,a.fRemark,fBuiltDate as fBulidDate,convert(varchar(10),'') as fDestineDate,a.fDeliverDate  as fDateKey," & vbCrLf
                    'Sql &= "    dbo.GetParentId(fAreaId) as fAreaId01,Isnull(fAreaId,'') as fAreaId02,a.fOrdeStatus,a.fGoodsType, " & vbCrLf
                    'Sql &= "    Convert(varchar(50),'') as TruckName " & vbCrLf
                    'Sql &= "    from Sal_SaleOrdeA a " & vbCrLf

                    'Sql &= "    where  a.fSaleOrdeNo in (select fSaleOrdeNo from [#" & TabC & "])" & vbCrLf & vbCrLf

                    'Sql &= "    DROP TABLE [#" & TabA & "]" & vbCrLf
                    'Sql &= "    DROP TABLE [#" & TabB & "]" & vbCrLf
                    'Sql &= "    DROP TABLE [#" & TabC & "]" & vbCrLf



            End Select

            'Dset = App.ReturnDataset(Sql)
            Dset = Exec(Sql, E_ExecType.DataSet)
            Me.frmDestineCustDetail.Set_Sal_SaleOrdeA = Dset.Tables(0)
            ModSys.Load_TreeView(Me.frmDestineCustDetail.Tvw_2_1, "全部", True, True)

        Catch ex As Exception
            MessageBox.Show("StepOperateSecord:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 返回第幾步定單查詢條件
    ''' </summary>
    ''' <param name="Index">setp </param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function Re_WhereExp_Step(ByVal Index As Integer) As String
        Dim Sql As String = " where 1=1 "
        Try
            If Index = 3 Then
                Sql &= "  and Isnull(fOrdeStatus,'A')='B'  and Isnull(fDeliverMode,'')='S2'  and Isnull(fAreaId,'')<>''  " ''倉送
            Else
                Sql &= "  and Isnull(fOrdeStatus,'A')='B'  and Isnull(fDeliverMode,'')='倉送'  and Isnull(fAreaId,'')<>''  " ''倉送
            End If

            Select Case Index
                Case 1

                Case 2
                    Dim TextValue As New System.Text.StringBuilder
                    For Each Node As TreeNode In Me.frmDestineCustDetail.Tvw_1_1.Nodes(0).Nodes
                        If Node.Checked = True Then
                            If TextValue.ToString.Trim <> "" Then
                                TextValue.Append(",")
                            End If
                            TextValue.Append(Node.Tag.ToString.Trim)
                        End If
                    Next
                    Dim fAreaId As String = "'" & TextValue.ToString.Trim.Replace(",", "','") & "'"
                    Sql &= "  and dbo.GetParentId(fAreaId) in (" & fAreaId & ")"

                    If Me.frmDestineCustDetail.CheckBox2.Checked = True Then
                        Sql &= "  and a.fSaleDate>='" & Format(Me.frmDestineCustDetail.dtpStartDate.Value, "yyyy-MM-dd") & "' and a.fSaleDate<='" & Format(Me.frmDestineCustDetail.dtpEndDate.Value, "yyyy-MM-dd") & "'"
                    End If


                    If Me.frmDestineCustDetail.Tvw_1_2.Nodes(0).Checked = True Then
                        ''全選情況
                    Else
                        Dim TextValueB As New System.Text.StringBuilder

                        For Each Node As TreeNode In Me.frmDestineCustDetail.Tvw_1_2.Nodes(0).Nodes
                            If Node.Checked = True Then
                                If TextValueB.ToString.Trim <> "" Then
                                    TextValueB.Append(",")
                                End If
                                TextValueB.Append("'")
                                TextValueB.Append(Node.Tag.ToString.Trim)
                                TextValueB.Append("'")
                            End If
                        Next
                        If TextValueB.ToString.Trim <> "" Then
                            Sql &= "  and Isnull(a.fGoodsType,'') in (" & TextValueB.ToString.Trim & ")  "
                        End If
                    End If

                    Select Case Me.frmDestineCustDetail.cbxfDestineStatus.Text

                        Case E_DestineStatus.未排.ToString

                            Sql &= "  and a.fSaleOrdeNo not in (select distinct fSaleOrdeNo from V_DeliverGoods)  "

                        Case E_DestineStatus.已排.ToString

                            Sql &= "  and a.fSaleOrdeNo in (select distinct fSaleOrdeNo from V_DeliverGoods)  "

                        Case Else

                    End Select

                    If Me.frmDestineCustDetail.CheckBox1.Checked = True Then
                        Sql &= "  and a.fDateKey>='" & Format(Me.frmDestineCustDetail.dtpfDeliverDateStart.Value, "yyyy-MM-dd") & "'  and a.fDateKey<='" & Format(Me.frmDestineCustDetail.dtpfDeliverDateEnd.Value, "yyyy-MM-dd") & "'"
                    End If
                Case 3
                    Dim TextValue As New System.Text.StringBuilder
                    For Each Node As TreeNode In Me.frmDestineCustDetail.Tvw_1_1.Nodes(0).Nodes
                        If Node.Checked = True Then
                            If TextValue.ToString.Trim <> "" Then
                                TextValue.Append(",")
                            End If
                            TextValue.Append(Node.Tag.ToString.Trim)
                        End If
                    Next
                    Dim fAreaId As String = "'" & TextValue.ToString.Trim.Replace(",", "','") & "'"
                    Sql &= "  and dbo.GetParentId(fAreaId) in (" & fAreaId & ")"

                    If Me.frmDestineCustDetail.CheckBox2.Checked = True Then
                        Sql &= "  and a.fSaleDate>='" & Format(Me.frmDestineCustDetail.dtpStartDate.Value, "yyyy-MM-dd") & "' and a.fSaleDate<='" & Format(Me.frmDestineCustDetail.dtpEndDate.Value, "yyyy-MM-dd") & "'"
                    End If

                    Sql &= "  and a.fSaleOrdeNo in (select  distinct fSaleOrdeNo from V_DeliverGoods)  "

                    If Me.frmDestineCustDetail.Tvw_1_2.Nodes(0).Checked = True Then
                        ''全選情況
                    Else
                        Dim TextValueB As New System.Text.StringBuilder

                        For Each Node As TreeNode In Me.frmDestineCustDetail.Tvw_1_2.Nodes(0).Nodes
                            If Node.Checked = True Then
                                If TextValueB.ToString.Trim <> "" Then
                                    TextValueB.Append(",")
                                End If
                                TextValueB.Append("'")
                                TextValueB.Append(Node.Tag.ToString.Trim)
                                TextValueB.Append("'")
                            End If
                        Next
                        If TextValueB.ToString.Trim <> "" Then
                            Sql &= "  and Isnull(a.fGoodsType,'') in (" & TextValueB.ToString.Trim & ")  "
                        End If
                    End If


                    If Me.frmDestineCustDetail.CheckBox1.Checked = True Then
                        Sql &= "  and a.fDateKey>='" & Format(Me.frmDestineCustDetail.dtpfDeliverDateStart.Value, "yyyy-MM-dd") & "'  and a.fDateKey<='" & Format(Me.frmDestineCustDetail.dtpfDeliverDateEnd.Value, "yyyy-MM-dd") & "'"
                    End If

                Case 4

                    Dim TextValue As New System.Text.StringBuilder
                    For Each Node As TreeNode In Me.frmDestineCustDetail.Tvw_1_1.Nodes(0).Nodes
                        If Node.Checked = True Then
                            If TextValue.ToString.Trim <> "" Then
                                TextValue.Append(",")
                            End If
                            TextValue.Append(Node.Tag.ToString.Trim)
                        End If
                    Next
                    Dim fAreaId As String = "'" & TextValue.ToString.Trim.Replace(",", "','") & "'"
                    Sql &= "  and dbo.GetParentId(fAreaId) in (" & fAreaId & ")"

                    If Me.frmDestineCustDetail.CheckBox2.Checked = True Then
                        Sql &= "  and b.fSaleDate>='" & Format(Me.frmDestineCustDetail.dtpStartDate.Value, "yyyy-MM-dd") & "' and b.fSaleDate<='" & Format(Me.frmDestineCustDetail.dtpEndDate.Value, "yyyy-MM-dd") & "'"
                    End If

                    If Me.frmDestineCustDetail.Tvw_1_2.Nodes(0).Checked = True Then
                        ''全選情況
                    Else
                        Dim TextValueB As New System.Text.StringBuilder

                        For Each Node As TreeNode In Me.frmDestineCustDetail.Tvw_1_2.Nodes(0).Nodes
                            If Node.Checked = True Then
                                If TextValueB.ToString.Trim <> "" Then
                                    TextValueB.Append(",")
                                End If
                                TextValueB.Append("'")
                                TextValueB.Append(Node.Tag.ToString.Trim)
                                TextValueB.Append("'")
                            End If
                        Next
                        If TextValueB.ToString.Trim <> "" Then
                            Sql &= "  and Isnull(b.fGoodsType,'') in (" & TextValueB.ToString.Trim & ")  "
                        End If
                    End If

                    If Me.frmDestineCustDetail.CheckBox1.Checked = True Then
                        Sql &= "  and Convert(varchar(10),b.fDeliverDate,21)>='" & Format(Me.frmDestineCustDetail.dtpfDeliverDateStart.Value, "yyyy-MM-dd") & "'  and Convert(varchar(10),b.fDeliverDate,21)<='" & Format(Me.frmDestineCustDetail.dtpfDeliverDateEnd.Value, "yyyy-MM-dd") & "'"
                    End If

                Case Else

            End Select


        Catch ex As Exception
            MessageBox.Show("Re_WhereExp_Step:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
        Return Sql
    End Function

    ''' <summary>
    ''' 返回第幾步定單查詢條件 [第二個版本]
    ''' </summary>
    ''' <param name="Index"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ReturnWhere_2(ByVal Index As Integer)
        Dim sql As String = ""
        Select Case Index
            Case 1

            Case 2
                sql &= " where 1=1  "
                Dim TextValue As New System.Text.StringBuilder
                For Each Node As TreeNode In Me.frmDestineCustDetail.Tvw_1_1.Nodes(0).Nodes
                    If Node.Checked = True Then
                        If TextValue.ToString.Trim <> "" Then
                            TextValue.Append(",")
                        End If
                        TextValue.Append(Node.Tag.ToString.Trim)
                    End If
                Next
                Dim fAreaId As String = TextValue.ToString.Trim

                sql &= "  and fAreaId01 in (" & fAreaId & ")"


                If Me.frmDestineCustDetail.CheckBox2.Checked = True Then
                    sql &= "  and a.fSaleDate>='" & Format(Me.frmDestineCustDetail.dtpStartDate.Value, "yyyy-MM-dd") & "' and a.fSaleDate<='" & Format(Me.frmDestineCustDetail.dtpEndDate.Value, "yyyy-MM-dd") & "'"
                End If


                If Me.frmDestineCustDetail.Tvw_1_2.Nodes(0).Checked = True Then
                    ''全選情況
                Else
                    Dim TextValueB As New System.Text.StringBuilder

                    For Each Node As TreeNode In Me.frmDestineCustDetail.Tvw_1_2.Nodes(0).Nodes
                        If Node.Checked = True Then
                            If TextValueB.ToString.Trim <> "" Then
                                TextValueB.Append(",")
                            End If
                            TextValueB.Append("'")
                            TextValueB.Append(Node.Tag.ToString.Trim)
                            TextValueB.Append("'")
                        End If
                    Next
                    If TextValueB.ToString.Trim <> "" Then
                        sql &= "  and Isnull(a.fGoodsType,'') in (" & TextValueB.ToString.Trim & ")  "
                    End If
                End If

                Select Case Me.frmDestineCustDetail.cbxfDestineStatus.Text

                    Case E_DestineStatus.未排.ToString

                        ''已報廢的單可以重新安排
                        sql &= "  and a.fSaleOrdeNo not in (select distinct a.fSaleOrdeNo from V_DeliverGoods a, Sal_SaleOrdeA b where Isnull(BillStatus,'')<>'E' and a.fSaleOrdeNo=b.fSaleOrdeNo)  "

                    Case E_DestineStatus.已排.ToString

                        sql &= "  and a.fSaleOrdeNo in (select distinct fSaleOrdeNo from V_DeliverGoods)  "

                    Case Else

                End Select

                If Me.frmDestineCustDetail.CheckBox1.Checked = True Then
                    sql &= "  and a.fDateKey>='" & Format(Me.frmDestineCustDetail.dtpfDeliverDateStart.Value, "yyyy-MM-dd") & "'  and a.fDateKey<='" & Format(Me.frmDestineCustDetail.dtpfDeliverDateEnd.Value, "yyyy-MM-dd") & "'"
                End If
        End Select
        Return sql
    End Function

    ''' <summary>
    ''' 驗證
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function Validated_Step() As Boolean
        Try
            Select Case Index
                Case 0

                Case 1
                    Dim I As Integer = 0

                    For Each Node As TreeNode In Me.frmDestineCustDetail.Tvw_1_1.Nodes(0).Nodes
                        If Node.Checked = True Then
                            I += 1
                            Exit For
                        End If
                    Next
                    If I = 0 Then
                        MessageBox.Show("請選擇一條路線。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                        Me.frmDestineCustDetail.Tvw_1_1.Focus()
                        Return False
                    End If

                    If Format(Me.frmDestineCustDetail.dtpStartDate.Value, "yyyy-MM-dd") > Format(Me.frmDestineCustDetail.dtpEndDate.Value, "yyyy-MM-dd") Then
                        MessageBox.Show("開始日期不能大於結束日期。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                        Me.frmDestineCustDetail.dtpStartDate.Focus()
                        SendKeys.Send("{F4}")
                        Return False
                    End If

                    Dim Bool As Boolean = False

                    If Me.frmDestineCustDetail.CheckBox2.Checked OrElse Me.frmDestineCustDetail.CheckBox1.Checked Then
                        Bool = True
                    End If

                    If Bool = False Then
                        MessageBox.Show("請選擇一個日期。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                        Me.frmDestineCustDetail.CheckBox2.Checked = True
                        Me.frmDestineCustDetail.dtpStartDate.Focus()
                        SendKeys.Send("{F4}")
                        Return False
                    End If
                Case Else

            End Select

            Return True
        Catch ex As Exception
            MessageBox.Show("Validated_Step:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK)
        End Try
    End Function

    ''' <summary>
    ''' 第三步
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub SetpOperateThree()
        Try

            Dim Dset As New DataSet
            Dim Sql As String = ""
            Dim WhereExp1 As String = Me.Re_WhereExp_Step(3)

            Sql &= "    select * from ("
            Sql &= "    select  Isnull(c.fDeliverId,'') as fDeliverId,a.Id,a.fSaleOrdeNo,a.fWriteNo,a.fDeliverMode,a.fDeliverDate,fCustomerId,b.Cnname as Cnname,a.fDeliverAddress,a.fLinkPhone as Telphone,LinkMan," & vbCrLf
            Sql &= "    fAreaId=case when Isnull(fAreaCode,'')='' then fAreaId else fAreaCode end,a.ShopNo,(select fShortName from BSC_StoreHouse d where Isnull(a.ShopNo,'')=Isnull(d.fCode,'')) as fShortName," & vbCrLf
            Sql &= "    a.fEmployeeId,(select fCName from BSC_Employee c where Isnull(a.fEmployeeId,'')=Isnull(c.fCode,'')) as fEmployeeName,fSaleDate,fOperaterMan,fOperateDate,fStoreCode," & vbCrLf
            Sql &= "    isnull (n.fDSIA,'0.00') as fDSIA,isnull (n.fDSIB,'0.00') as fDSIB,isnull (n.fBSI,'0.00') as fBSI, isnull (a.fTAmount,'0.00') as fTAmount,fPayMode,a.fRemark,fBuiltDate as fBulidDate,c.fDeliverDate as fDestineDate,case when Isnull(c.fDeliverDate,'')='' then a.fDeliverDate else c.fDeliverDate end  as fDateKey," & vbCrLf
            Sql &= "    dbo.GetParentId(case when Isnull(fAreaCode,'')='' then fAreaId else fAreaCode end) as fAreaId01,case when Isnull(fAreaCode,'')='' then fAreaId else fAreaCode end as fAreaId02,a.fOrdeStatus,a.fGoodsType,c.fTructCode " & vbCrLf
            Sql &= "    from Sal_SaleOrdeA a " & vbCrLf
            Sql &= "    left join BSC_Customer b on Isnull(a.fCustomerId,'')=Isnull(Convert(varchar(50),b.Id),'')" & vbCrLf
            Sql &= "    left join V_DeliverGoods c on (a.fSaleOrdeNo=c.fSaleOrdeNo) left join (select * from Sal_InvoiceA where FType='DEPOSIT')n ON a.fSaleOrdeNo = n.FSaleOrdeNo  ) a " & WhereExp1 & vbCrLf & vbCrLf

            Dset = App.ReturnDataset(Sql)

            Me.frmDestineCustDetail.Set_Sal_SaleOrdeAP = Dset.Tables(0)

            ModSys.Load_TreeView(Me.frmDestineCustDetail.Tvw_3_1, "全部")

        Catch ex As Exception
            MessageBox.Show("SetpOperateThree:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

#End Region

#Region "添加事件"

    ''' <summary>
    ''' KeyDown 事件
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Text_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
        Try
            Select Case e.KeyCode
                Case Keys.Enter
                    If e.Shift = True Then
                        If TypeOf sender Is ComboBox AndAlso CType(sender, ComboBox).DroppedDown = True Then
                            CType(sender, ComboBox).DroppedDown = False
                        End If
                        SendKeys.Send("+{Tab}")
                        SendKeys.Send("{F4}")
                    Else
                        If TypeOf sender Is ComboBox AndAlso CType(sender, ComboBox).DroppedDown = True Then
                            CType(sender, ComboBox).DroppedDown = False
                        End If
                        SendKeys.Send("{Tab}")
                        SendKeys.Send("{F4}")
                    End If
                Case Else

            End Select
        Catch ex As Exception
            MessageBox.Show("Text_KeyDown:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 添加事件
    ''' </summary>
    ''' <param name="Pans"></param>
    ''' <remarks></remarks>
    Private Sub AddHandlers(ByVal Pans() As Control)
        Try
            For Each Pan As Control In Pans
                For Each Ctrl As Control In Pan.Controls
                    If TypeOf Ctrl Is TextBox _
                       OrElse TypeOf Ctrl Is ComboBox _
                       OrElse TypeOf Ctrl Is NumericUpDown _
                       OrElse TypeOf Ctrl Is MaskedTextBox _
                       OrElse TypeOf Ctrl Is DateTimePicker Then
                        AddHandler Ctrl.KeyDown, AddressOf Text_KeyDown
                    End If
                Next
            Next
        Catch ex As Exception
            MessageBox.Show("AddHandlers:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

#End Region

#Region "狀態控制"

    ''' <summary>
    ''' 設置按鈕狀態
    ''' </summary>
    ''' <param name="type">操作類型</param>
    ''' <param name="IsFind">是否是流覽</param>
    ''' <remarks></remarks>
    Private Sub SetButton(ByVal type As ButtonType, ByVal IsFind As Boolean)
        Try

            Dim fCurrentBool As Boolean = False

            Dim fStatus As String = ""

            If Not Me.DGView_1_1.CurrentRow Is Nothing AndAlso Me.TabControl1.SelectedIndex = 0 Then
                fCurrentBool = True
                fStatus = Me.DGView_1_1.CurrentRow.Cells("fStatus").Value.ToString.Trim & ""
            End If

            Me.btnPrintInv.Enabled = IsFind AndAlso fCurrentBool AndAlso (fStatus.ToLower = "B".ToLower)
            Dim TabIndex As Integer = Me.TabControl1.SelectedIndex

            Select Case type
                Case ButtonType.Add
                    With MainForm
                        .ToolStripAdd.Enabled = False
                        .ToolStripEdit.Enabled = False
                        .ToolStripDelete.Enabled = False
                        .ToolStripSave.Enabled = True
                        .ToolStripCancel.Enabled = True
                        .ToolStripFirst.Enabled = False
                        .ToolStripLast.Enabled = False
                        .ToolStripNext.Enabled = False
                        .ToolStripPrivous.Enabled = False
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True

                    End With

                Case ButtonType.Browse
                    With MainForm
                        .ToolStripAdd.Enabled = False
                        .ToolStripEdit.Enabled = IsFind AndAlso fCurrentBool AndAlso (fStatus.ToLower = "A".ToLower OrElse fStatus.ToLower = "C".ToLower)
                        '.ToolStripDelete.Enabled = IsFind AndAlso fCurrentBool AndAlso (fStatus.ToLower = "A".ToLower OrElse fStatus.ToLower = "C".ToLower)

                        .ToolStripDelete.Enabled = False
                        .ToolStripSave.Enabled = False
                        .ToolStripCancel.Enabled = False
                        .ToolStripFirst.Enabled = False
                        .ToolStripLast.Enabled = False
                        .ToolStripNext.Enabled = False
                        .ToolStripPrivous.Enabled = False
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True
                        .ToolStripCheck.Enabled = IsFind AndAlso (fStatus.ToLower = "A".ToLower OrElse fStatus.ToLower = "C".ToLower) AndAlso TabIndex = 0
                        .ToolStripComplete.Enabled = IsFind AndAlso (fStatus.ToLower = "B".ToLower) AndAlso TabIndex = 0
                        .ToolStripUnCheck.Enabled = IsFind AndAlso (fStatus.ToLower = "B".ToLower) AndAlso TabIndex = 0
                    End With

                Case ButtonType.Cancel
                    With MainForm
                        .ToolStripAdd.Enabled = True
                        .ToolStripEdit.Enabled = IsFind AndAlso fCurrentBool
                        .ToolStripDelete.Enabled = IsFind AndAlso fCurrentBool
                        .ToolStripSave.Enabled = False
                        .ToolStripCancel.Enabled = False
                        .ToolStripFirst.Enabled = IsFind
                        .ToolStripLast.Enabled = IsFind
                        .ToolStripNext.Enabled = IsFind
                        .ToolStripPrivous.Enabled = IsFind
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True

                    End With

                Case ButtonType.Edit
                    With MainForm
                        .ToolStripAdd.Enabled = False
                        .ToolStripEdit.Enabled = False
                        .ToolStripDelete.Enabled = False
                        .ToolStripSave.Enabled = True
                        .ToolStripCancel.Enabled = True
                        .ToolStripFirst.Enabled = False
                        .ToolStripLast.Enabled = False
                        .ToolStripNext.Enabled = False
                        .ToolStripPrivous.Enabled = False
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True

                    End With

            End Select
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub SetCtrlEnabled(ByVal bEanbled As Boolean)
        Dim bReadonly As Boolean = Not bEanbled
        Me.txtfTruckName.ReadOnly = bReadonly
        Me.txtRemark.ReadOnly = bReadonly
        Me.btnPrintInv.Enabled = False
    End Sub

#End Region

#Region "數據處理"

    ''' <summary>
    ''' 驗證
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function Validated1() As Boolean
        Try
            Me.DGView_2_1.EndEdit()
            Me.DGView_2_1.Update()
            Dim I As Integer = Me.DGView_2_1.RowCount
            If I = 0 Then
                MessageBox.Show("沒有一條記錄，不能保存。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                Me.DGView_2_1.Focus()
                Return False
            End If

            Dim Dtab As DataTable = DirectCast(Me.DGView_2_1.DataSource, DataTable)

            For I = 0 To Me.DGView_2_1.RowCount - 1
                Dim SiteNo As Integer = Val(Me.DGView_2_1.Rows(I).Cells("SiteNo").Value & "")
                If SiteNo <> 0 Then
                    If SiteNo < 0 Then
                        MessageBox.Show("站點不能為負數。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                        Me.DGView_2_1.Focus()
                        Me.DGView_2_1.CurrentCell = Me.DGView_2_1.Rows(I).Cells("SiteNo")
                        Me.DGView_2_1.CurrentRow.Selected = True
                        Me.DGView_2_1.BeginEdit(True)
                        Return False
                    Else
                        Dim DRow() As DataRow = Dtab.Select("SiteNo=" & SiteNo & "")
                        If DRow.Length > 1 Then
                            MessageBox.Show("存在重複的站點。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                            Me.DGView_2_1.Focus()
                            Me.DGView_2_1.CurrentCell = Me.DGView_2_1.Rows(I).Cells("SiteNo")
                            Me.DGView_2_1.CurrentRow.Selected = True
                            Me.DGView_2_1.BeginEdit(True)
                            Return False
                        End If
                    End If
                End If

                '    Dim fAddressName As String = Me.DGView_2_1.Rows(I).Cells("fAddressName").Value.ToString.Trim & ""
                '    If fAddressName.Trim = "" Then
                '        MessageBox.Show("送貨地址不能為空。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                '        Me.DGView_2_1.Focus()
                '        Me.DGView_2_1.CurrentCell = Me.DGView_2_1.Rows(I).Cells("fAddressName")
                '        Me.DGView_2_1.CurrentRow.Selected = True
                '        Me.DGView_2_1.BeginEdit(True)
                '        Return False
                '    End If
                '    Dim fTelphone As String = Me.DGView_2_1.Rows(I).Cells("fTelphone").Value.ToString.Trim
                '    If fTelphone.Trim = "" Then
                '        MessageBox.Show("聯系電話不能為空。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                '        Me.DGView_2_1.Focus()
                '        Me.DGView_2_1.CurrentCell = Me.DGView_2_1.Rows(I).Cells("fTelphone")
                '        Me.DGView_2_1.CurrentRow.Selected = True
                '        Me.DGView_2_1.BeginEdit(True)
                '        Return False
                '    End If
                '    Dim fConsigneeMan As String = Me.DGView_2_1.Rows(I).Cells("fConsigneeMan").Value.ToString.Trim & ""
                '    If fConsigneeMan.Trim = "" Then
                '        MessageBox.Show("聯系人不能為空。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                '        Me.DGView_2_1.Focus()
                '        Me.DGView_2_1.CurrentCell = Me.DGView_2_1.Rows(I).Cells("fConsigneeMan")
                '        Me.DGView_2_1.CurrentRow.Selected = True
                '        Me.DGView_2_1.BeginEdit(True)
                '        Return False
                '    End If
            Next
            Return True
        Catch ex As Exception
            MessageBox.Show("Validated1:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Function

    ''' <summary>
    ''' 保存數據
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function btnSaveData() As Boolean
        Try
            If Me.Validated1() = False Then Return False

            Dim MasterDtab As DataTable = DirectCast(Me.DGView_2_1.DataSource, DataTable)

            Dim TextValue As New System.Text.StringBuilder

            Dim Sql As String = ""
            Dim SqlCn As SqlConnection = GetConn()
            Dim SqlCmd As New SqlCommand
            Dim SqlTran As SqlTransaction = SqlCn.BeginTransaction
            Dim SqlBluck As SqlBulkCopy

            Try

                Dim fDeliverId As String = Me.txtfDeliverId.Text.Trim

                Dim Remark As String = Replace_Text(Me.txtRemark.Text.Trim)
                Dim UpdatePsn As String = PubUserName
                Dim UpdateDate As Date = ServerDate
                Dim UpdateComputer As String = My.Computer.Name

                Dim DetailDtab As New DataTable
                DetailDtab = Me.Re_DeliverGoodsDetail(MasterDtab, TextValue, 1)

                Sql &= " Update DeliverGoodsMaster set  Remark='" & Remark & "',UpdatePsn='" & UpdatePsn & "',UpdateDate=getdate(),UpdateComputer='" & UpdateComputer & "'  where   Isnull(fDeliverId,'')='" & fDeliverId & "'" & vbCrLf & vbCrLf

                Sql &= " Delete dbo.DeliverGoodsDetail where Isnull(fDeliverId,'')='" & fDeliverId & "' and fSaleOrdeNo in (" & TextValue.ToString.Trim & ")" & vbCrLf & vbCrLf

                With SqlCmd
                    .CommandText = Sql
                    .CommandType = CommandType.Text
                    .Connection = SqlCn
                    .Transaction = SqlTran
                    .ExecuteNonQuery()
                End With

                SqlBluck = New SqlBulkCopy(SqlCn, SqlBulkCopyOptions.Default, SqlTran)
                With SqlBluck
                    .DestinationTableName = "DeliverGoodsDetail"
                    .BulkCopyTimeout = 100
                    .WriteToServer(DetailDtab)
                End With

                SqlTran.Commit()

                Dim DtabA As DataTable = DirectCast(Me.DGView_1_1.DataSource, DataTable)

                Dim DRow() As DataRow = DtabA.Select("fDeliverId='" & fDeliverId & "'")
                If DRow.Length > 0 Then
                    DRow(0).Item("Remark") = Remark
                    DRow(0).Item("UpdatePsn") = UpdatePsn
                    DRow(0).Item("UpdateDate") = Format(UpdateDate, "yyyy-MM-dd")
                    DRow(0).Item("UpdateComputer") = UpdateComputer
                End If
                DtabA.AcceptChanges()
                Me.DGView_1_1.Update()
                MasterDtab.AcceptChanges()

            Catch ex As Exception
                SqlTran.Rollback()
                MessageBox.Show(My.Resources.ErrEdit, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                Return False
            End Try
            MessageBox.Show(My.Resources.EditSuccess, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
            SetButton(ButtonType.Browse, True)
            SetDataGridViewEnabledColumn(Me.DGView_2_1, Me.Re_EnabledColumnEdit(), True)
            SetCtrlEnabled(False)
            Return True
        Catch ex As Exception
            MessageBox.Show("btnSaveData:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Function

    ''' <summary>
    ''' FullFormatDataGridView(Me.DGView_1_1)
    ''' </summary>
    ''' <param name="SourDtab"></param>
    ''' <param name="TextValue"></param>
    ''' <param name="Index"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function Re_DeliverGoodsDetail(ByVal SourDtab As DataTable, ByRef TextValue As System.Text.StringBuilder, ByVal Index As Integer) As DataTable
        Dim Dtab As New DataTable
        Try
            With Dtab.Columns

                .Add("fDeliverId", GetType(System.String))
                .Add("fSaleOrdeNo", GetType(System.String))
                .Add("SiteNo", GetType(System.String))
                .Add("fAddressName", GetType(System.String))
                .Add("fConsigneeMan", GetType(System.String))
                .Add("fTelphone", GetType(System.String))
                .Add("fAecceptDate", GetType(System.String))
                .Add("fRemark", GetType(System.String))
                .Add("Ticket", GetType(System.Int32))
                .Add("fStatus", GetType(System.String))
                .Add("fSplitStatus", GetType(System.Int32))
                .Add("OutStoreHouse", GetType(System.String))
                .Add("FNum", GetType(System.String))
                .Add("BillStatus", GetType(System.String))
                .Add("fDStatus", GetType(System.String))
                ''如果修改表要在這裏添加相應的列

            End With

            Select Case Index
                Case 1

                    For Each Row As DataRow In SourDtab.Rows
                        Dim MRow As DataRow = Dtab.NewRow
                        MRow("fDeliverId") = Row("fDeliverId")
                        MRow("fSaleOrdeNo") = Row("fSaleOrdeNo")
                        MRow("SiteNo") = Val(Row("SiteNo") & "")
                        MRow("fAddressName") = Row("fAddressName")
                        MRow("fConsigneeMan") = Row("fConsigneeMan")
                        MRow("fTelphone") = Row("fTelphone")
                        MRow("fAecceptDate") = Row("fAecceptDate") & ""
                        MRow("fRemark") = Row("fRemark")

                        If Row("Ticket") & "" = "是" Then
                            MRow("Ticket") = 1
                        Else
                            MRow("Ticket") = 0
                        End If

                        MRow("fStatus") = Val(Row("fStatus") & "")
                        MRow("fSplitStatus") = Val(Row("fSplitStatus") & "")

                        MRow("OutStoreHouse") = Row("fOutStoreHouse") & ""
                        MRow("FNum") = Row("FNum") & ""
                        MRow("BillStatus") = IIf((Row("BillStatus") & "") = "", "A", Row("BillStatus") & "")
                        MRow("fDStatus") = Val(Row("fDStatus") & "")

                        If TextValue.ToString.Trim <> "" Then
                            TextValue.Append(",")
                        End If
                        TextValue.Append("'" & Row("fSaleOrdeNo") & "'")

                        Dtab.Rows.Add(MRow)
                    Next

                Case Else

            End Select

        Catch ex As Exception
            MessageBox.Show("Re_DeliverGoodsDetail:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
        Return Dtab
    End Function

    ''' <summary>
    ''' 組裝生成尾數發票
    ''' </summary>
    ''' <param name="ShopNo">門店</param>
    ''' <param name="FSaleOrdeNo">銷售單號</param>
    ''' <param name="FWriteNo">手寫單號</param>
    ''' <param name="fCheckDate">審核日期</param>
    ''' <param name="fDeliverId">送貨單號</param>
    ''' <param name="fCheckMan">審核人</param>
    ''' <param name="fCheckComputer">電腦</param>
    ''' <returns>string</returns>
    ''' <remarks></remarks>
    Private Function PerpareCommandInv(ByVal ShopNo As String, ByVal FSaleOrdeNo As String, ByVal FWriteNo As String, _
                                       ByVal fCheckDate As String, ByVal fDeliverId As String, ByVal fCheckMan As String, ByVal fCheckComputer As String) As String
        Dim TextStr As String = ""

        TextStr &= "  select @FValue=FValue from BSC_SystemProfile where FCategory='AR' and FKey='NeedCheck' " & vbCrLf

        TextStr &= "select @FPayInFull=Max(Convert(int,FPayInFull)) from dbo.Sal_InvoiceA where fSaleOrdeNo='" & FSaleOrdeNo & "' and fType='DEPOSIT' " & vbCrLf

        TextStr &= "set @FBSI=0.00" & vbCrLf

        TextStr &= " if @FValue='Y'" & vbCrLf
        TextStr &= "    Begin" & vbCrLf
        '' TextStr &= "    if @FPayInFull<>1" & vbCrLf  modified by jason
        TextStr &= "        Begin" & vbCrLf
        TextStr &= "            select  @FBSI=(select Isnull(Sum(fSumMoney),0) from dbo.Sal_SaleOrdeB where fSaleordeNo='" & FSaleOrdeNo & "')" & vbCrLf
        TextStr &= "            -(select Isnull(Sum(FDSIA),0) from Sal_InvoiceA  where fSaleordeNo='" & FSaleOrdeNo & "' and fType='DEPOSIT' and BillStatusId in ('B','F'))" & vbCrLf
        TextStr &= "            -(select Isnull(Sum(FReceipt),0) from Sal_InvoiceA  where fSaleordeNo='" & FSaleOrdeNo & "' and fType='BALANCE'  and BillStatusId in ('B','F'))" & vbCrLf
        TextStr &= "        End" & vbCrLf
        TextStr &= "    End" & vbCrLf
        TextStr &= " Else" & vbCrLf
        TextStr &= "    Begin" & vbCrLf
        ''TextStr &= "    if @FPayInFull=1" & vbCrLf
        TextStr &= "        Begin" & vbCrLf
        TextStr &= "            select  @FBSI=(select Isnull(Sum(fSumMoney),0) from dbo.Sal_SaleOrdeB where fSaleordeNo='" & FSaleOrdeNo & "')" & vbCrLf
        TextStr &= "            -(select Isnull(Sum(FDSIA),0) from Sal_InvoiceA  where fSaleordeNo='" & FSaleOrdeNo & "' and fType='DEPOSIT'  and BillStatusId not in ('D','E'))" & vbCrLf
        TextStr &= "            -(select Isnull(Sum(FReceipt),0) from Sal_InvoiceA  where fSaleordeNo='" & FSaleOrdeNo & "' and fType='BALANCE'  and BillStatusId not in ('D','E'))" & vbCrLf
        TextStr &= "        End" & vbCrLf
        TextStr &= "    End" & vbCrLf

        ''Fnum
        TextStr &= "  select  @FNum=dbo.getMaxNum('SalInvoice')" & vbCrLf

        TextStr &= "  Insert Into Sal_InvoiceA(FNum,FDate,ShopNo,FSaleOrdeNo,FDeliverId,FWriteNo,FType,BulidBy,BulidDate,BulidComputer,BillStatusId,FDSIA,FDSIB,FBSI,FTAmount)" & vbCrLf
        TextStr &= "  values(@FNum,'" & fCheckDate & "','" & ShopNo & "','" & FSaleOrdeNo & "','" & fDeliverId & "','" & FWriteNo & "','BALANCE','" & fCheckMan & "','" & fCheckDate & "','" & fCheckComputer & "','A',0.00,@FBSI,0,@FBSI)" & vbCrLf & vbCrLf

        TextStr &= "  Update DeliverGoodsDetail set FNum=@FNum where Isnull(fDeliverId,'')='" & fDeliverId & "' and Isnull(fSaleOrdeNo,'')='" & FSaleOrdeNo & "'" & vbCrLf
        ''Fnum+1
        TextStr &= "  Update Number set Number=Replace(@FNum,'INV','')  where BillType='SalInvoice' " & vbCrLf

        Return TextStr

    End Function

#End Region

#Region "審核反審核"

    Private Function ActionChecked_0() As Boolean

    End Function

#End Region

#Region "打印"

#End Region

#End Region

#Region "Controls Events"

#Region "窗體加載"

    Private Sub Frm_OFSArrangeDelivery_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            Me.fLoadBool = False
            ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
            Initialize()
            AddHandlers(New Control() {Me.GroupBox1, Me.Panel4})
            AddHandlers_IContexMenu(Me.ContextMenuStrip1)
            setControlsbEnabled(New Control() {Me.Panel4}, False)
            Dim WhereExp As String = Me.Re_WhereExp()
            Me.ExecFind(WhereExp)
            FillDetail()
            FillDetailGrid()
            FullFormatDataGridView(Me.DGView_2_1)
            FullFormatDataGridView(Me.DGView_2_2, False, False, False)
            FullFormatDataGridView(Me.DGView_1_1)
            Me.fLoadBool = True
            Me.OrdeModeItem()
        Catch ex As Exception
            MessageBox.Show("Frm_OFSArrangeDelivery_Load:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

#End Region

#Region "TreeView Events"

#End Region

#Region "位置控制"


    Private Sub Panel2_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Panel2.Resize
        Try
            Me.Panel3.Left = (Me.Panel2.Width - Me.Panel3.Width) / 3 * 2
            Me.Panel3.Top = (Me.Panel2.Height - Me.Panel3.Height) / 2
        Catch ex As Exception
            MessageBox.Show("Panel2_Resize:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub Panel4_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Panel4.Resize
        Try

            Me.lbSplter1.Width = Me.Panel4.Width - 2
            Me.lbSplter1.Left = Me.Panel4.Left

        Catch ex As Exception
            MessageBox.Show("Panel4_Resize:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

#End Region

#Region "按鈕事件"

    ''' <summary>
    ''' 向前
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnPrevious_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrevious.Click
        Try
            Index -= 1
            AddTabpage()
            Me.setBtnEnabled()
            SetpOperate()
        Catch ex As Exception
            MessageBox.Show("btnPrevious_Click:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 向後
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnNext_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNext.Click
        Try
            Me.Cursor = Cursors.WaitCursor
            If Validated_Step() = False Then Exit Sub
            Index += 1
            AddTabpage()
            Me.setBtnEnabled()
            AddTabBool = True
            SetpOperate()
            AddTabBool = False
        Catch ex As Exception
            MessageBox.Show("btnNext_Click:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    ''' <summary>
    ''' 查詢
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnFind_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFind.Click
        Try
            Dim WhereExp As String = Me.Re_WhereExp
            ExecFind(WhereExp)
        Catch ex As Exception
            MessageBox.Show("btnFind_Click:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub


    ''' <summary>
    ''' 打印尾數發票
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnPrintInv_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrintInv.Click
        Dim Frm As New Frm_Wating
        Frm.Show()
        Try

            If Me.DGView_1_1.CurrentRow Is Nothing Then Exit Sub

            Dim Sql As String = ""
            Dim fDeliverId As String = Me.DGView_1_1.CurrentRow.Cells("fDeliverId").Value & ""

            Sql &= " Exec Print_InvBALANCEB '" & fDeliverId & "'" & vbCrLf

            Dim Dtab As DataTable = Exec(Sql, E_ExecType.DataTable)

            Dim IntRow As Integer = 10
            Dim FileName As String = ""
            FileName = GetReportPath("Delievry", "Print_InvBALANCE.rpt")
            If System.IO.File.Exists(FileName) = False Then
                MessageBox.Show("報表文件不存在!", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit Sub
            End If

            Dim MyRepDoc As New CrystalDecisions.CrystalReports.Engine.ReportDocument

            MyRepDoc.Load(FileName)

            ''Set Report Loginfo
            SetCrystalReportLoginfo(MyRepDoc)

            MyRepDoc.SetDataSource(Dtab)
            My.Forms.Frm_Report.CrystalReportViewer1.ReportSource = MyRepDoc
            My.Forms.Frm_Report.CrystalReportViewer1.RefreshReport()
            My.Forms.Frm_Report.CrystalReportViewer1.DisplayGroupTree = False
            Frm.Dispose()
            Frm_Report.ShowDialog()

        Catch ex As Exception
            MessageBox.Show("btnPrintInv_Click:" & ex.Message)
        Finally
            Frm = Nothing
        End Try
    End Sub

#End Region

#Region "網格事件"

    ''' <summary>
    ''' 網格DoubleClick
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub DGView_1_1_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGView_1_1.CellDoubleClick
        Try
            Me.TabControl2.SelectedIndex = 1
        Catch ex As Exception
            MessageBox.Show("DGView_1_1_CellDoubleClick:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub


    Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, ByVal keyData As System.Windows.Forms.Keys) As Boolean
        Try
            Const WM_KEYDOWN As Integer = &H100
            Const WM_SYSKEYDOWN As Integer = &H104
            'If TypeOf Me.ActiveControl Is DataGridView Then
            If ((msg.Msg = WM_KEYDOWN) Or (msg.Msg = WM_SYSKEYDOWN)) Then
                Select Case keyData
                    Case Keys.Enter
                        SendKeys.Send("{Tab}")
                        SendKeys.Send("{F4}")
                        'Return True
                    Case (Keys.Enter Or Keys.Shift)
                        SendKeys.Send("+{Tab}")
                        SendKeys.Send("{F4}")
                        'Return True
                End Select
            End If


            'End If
            Return MyBase.ProcessCmdKey(msg, keyData)
        Catch ex As Exception
            MessageBox.Show("ProcessCmdKey:" & ex.Message & ex.StackTrace)
        End Try
    End Function

    Private Sub DGView_2_1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DGView_2_1.KeyDown
        Try

        Catch ex As Exception
            MessageBox.Show("DGView_2_1_KeyDown:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub DGView_1_1_CurrentCellChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DGView_1_1.CurrentCellChanged
        'SetButton(ButtonType.Browse, True)
    End Sub

    ''' <summary>
    ''' 網格數據綁定完成
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub DGView_1_1_DataBindingComplete(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs) Handles DGView_1_1.DataBindingComplete
        Try
            'Dim DGView As DataGridView = DirectCast(sender, DataGridView)
            'SetDataGridViewBackColor(DGView, "fStatus")
        Catch ex As Exception
            MessageBox.Show("DGView_1_1_DataBindingComplete:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 數據綁定完成
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub DGView_2_2_DataBindingComplete(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs) Handles DGView_2_2.DataBindingComplete

    End Sub

    ''' <summary>
    ''' 繪制行號
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub DGView_1_1_RowPostPaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles DGView_1_1.RowPostPaint, DGView_2_1.RowPostPaint, DGView_2_2.RowPostPaint
        App.DGV_RowPostPaint(sender, e)
    End Sub

    ''' <summary>
    ''' 當前活動單元格改變
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub DGView_2_1_CurrentCellChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DGView_2_1.CurrentCellChanged
        Try

        Catch ex As Exception
            MessageBox.Show("DGView_2_1_CurrentCellChanged:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 選擇區域改變
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub DGView_2_1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DGView_2_1.SelectionChanged
        Try
            Dim DView As DataGridView = DirectCast(sender, DataGridView)
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                Me.DGView_2_2.EndEdit()
                Me.DGView_2_2.Update()
            End If
            Dim fDeliverId As String = ""
            Dim fSaleOrdeNo As String = ""
            If Not DView.CurrentRow Is Nothing Then
                fDeliverId = DView.CurrentRow.Cells("fDeliverId").Value & ""
                fSaleOrdeNo = DView.CurrentRow.Cells("fSaleOrdeNo").Value & ""
            End If
            Me.FillDetailGrid(fDeliverId, fSaleOrdeNo)
        Catch ex As Exception
            MessageBox.Show("DGView_2_1_SelectionChanged:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 選擇區域改變
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub DGView_1_1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DGView_1_1.SelectionChanged
        Try
            Dim DGView As DataGridView = DirectCast(sender, DataGridView)
            If DGView.CurrentRow Is Nothing Then Exit Sub
            SetButton(ButtonType.Browse, True)
        Catch ex As Exception
            MessageBox.Show("DGView_1_1_SelectionChanged:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 重設背景色
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub DGView_1_1_Sorted(ByVal sender As Object, ByVal e As System.EventArgs) Handles DGView_1_1.Sorted
        If Me.DGView_1_1.Rows.Count <= 0 Then Exit Sub
        Dim DGView As DataGridView = DirectCast(sender, DataGridView)
        SetDataGridViewBackColor(Me.DGView_1_1, "Status")
    End Sub

#End Region

#Region "TabControl事件"

    Private Sub TabControl2_Selected(ByVal sender As Object, ByVal e As System.Windows.Forms.TabControlEventArgs) Handles TabControl2.Selected
        Try
            If Me.TabControl2.SelectedIndex = 1 Then
                FillDetail()
            End If
        Catch ex As Exception
            MessageBox.Show("TabControl2_Selected:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub TabControl1_Selected(ByVal sender As Object, ByVal e As System.Windows.Forms.TabControlEventArgs) Handles TabControl1.Selected
        Dim TabIndex As Integer = Me.TabControl1.SelectedIndex
        SetButton(ButtonType.Browse, True)
        If TabIndex = 1 Then

        End If
    End Sub

    Private Sub TabControl2_Selecting(ByVal sender As Object, ByVal e As System.Windows.Forms.TabControlCancelEventArgs) Handles TabControl2.Selecting, TabControl1.Selecting
        If ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
            e.Cancel = True
        End If
    End Sub

#End Region

#Region "驗證數據"

    ''' <summary>
    ''' 驗證查詢過程
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function Validated_ExecFind() As Boolean
        Try


            If IsDate(Me.dtp_StartDate.Text.Trim) = True AndAlso IsDate(Me.dtp_EndDate.Text.Trim) = True Then
                If Me.dtp_StartDate.Text.Trim > Me.dtp_EndDate.Text.Trim Then
                    MessageBox.Show("開始日期不能大於結束日期。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                    Me.dtp_StartDate.Focus()
                    Return False
                End If
            End If

            Return True
        Catch ex As Exception
            MessageBox.Show("Validated_ExecFind:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Function

#End Region

#End Region

#Region "Interface Define"

    Public Function ActionAdd() As Boolean Implements IDServer.IDServer.IDServer.ActionAdd
        Try
            If AddEnable = False Then
                MessageBox.Show("對不起，您沒有新增權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If

            MainForm.ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
            Me.TabControl1.SelectedIndex = 1
            Return True
        Catch ex As Exception
            MessageBox.Show("ActionAdd:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Function

    ''' <summary>
    ''' 取消
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ActionCancel() As Boolean Implements IDServer.IDServer.IDServer.ActionCancel
        Try
            ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
            SetButton(ButtonType.Browse, True)
            SetDataGridViewEnabledColumn(Me.DGView_2_1, Me.Re_EnabledColumnEdit(), True)
            SetCtrlEnabled(False)
            Return True
        Catch ex As Exception
            MessageBox.Show("ActionCancel:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Function

    Public Function ActionDelete() As Boolean Implements IDServer.IDServer.IDServer.ActionDelete

    End Function

    ''' <summary>
    ''' 修改
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ActionEdit() As Boolean Implements IDServer.IDServer.IDServer.ActionEdit
        Try
            If EditEnable = False Then
                MessageBox.Show("對不起，您沒有修改權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If

            If Me.TabControl2.SelectedIndex <> 1 Then
                Me.TabControl2.SelectedIndex = 1
            End If
            ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit
            SetCtrlEnabled(True)
            SetButton(ButtonType.Edit, False)
            Me.DGView_2_1.ReadOnly = False
            SetDataGridViewEnabledColumn(Me.DGView_2_1, Me.Re_EnabledColumnEdit())
            Return True
        Catch ex As Exception
            MessageBox.Show("ActionEdit:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Function

    Public Function ActionExport() As Boolean Implements IDServer.IDServer.IDServer.ActionExport

    End Function

    Public Function ActionFilter() As Boolean Implements IDServer.IDServer.IDServer.ActionFilter

    End Function

    Public Function ActionGoFirst() As Boolean Implements IDServer.IDServer.IDServer.ActionGoFirst

    End Function

    Public Function ActionGoLast() As Boolean Implements IDServer.IDServer.IDServer.ActionGoLast

    End Function

    Public Function ActionGoNext() As Boolean Implements IDServer.IDServer.IDServer.ActionGoNext

    End Function

    Public Function ActionGoPrevious() As Boolean Implements IDServer.IDServer.IDServer.ActionGoPrevious

    End Function

    Public Function ActionImport() As Boolean Implements IDServer.IDServer.IDServer.ActionImport

    End Function

    Public Function ActionInitialize() As Boolean Implements IDServer.IDServer.IDServer.ActionInitialize

    End Function

    ''' <summary>
    ''' 打印行程表
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ActionPrint() As Boolean Implements IDServer.IDServer.IDServer.ActionPrint

        Dim Frm As New Frm_Wating

        Try
            Me.Cursor = Cursors.WaitCursor

            If Me.DGView_1_1.CurrentRow Is Nothing Then Exit Function
            Frm.Show()
            Dim fDeliverId As String = Me.DGView_1_1.CurrentRow.Cells("fDeliverId").Value & ""

            Dim Dset As New DataSet

            Dim Sql As String = " "
            Sql &= " Exec [Select_Delivery] '" & fDeliverId & "'" & vbCrLf


            Dset = Exec(Sql, E_ExecType.DataSet)

            Dim myReportDoc As New CrystalDecisions.CrystalReports.Engine.ReportDocument
            Dim myParameterValues As New CrystalDecisions.Shared.ParameterValues
            Dim myDiscreteValue As New CrystalDecisions.Shared.ParameterDiscreteValue

            Dim FileName As String = ""
            FileName = GetReportPath("Delievry", "Rep_YP.rpt")
            If System.IO.File.Exists(FileName) = False Then
                MessageBox.Show("報表文件不存在!", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                Return False
            End If

            myReportDoc.Load(FileName)

            SetCrystalReportLoginfo(myReportDoc)

            myReportDoc.SetDataSource(Dset.Tables(0))

            My.Forms.Frm_Report.CrystalReportViewer1.ReportSource = myReportDoc
            My.Forms.Frm_Report.CrystalReportViewer1.RefreshReport()

            My.Forms.Frm_Report.CrystalReportViewer1.DisplayGroupTree = False
            Frm.Dispose()
            Frm_Report.ShowDialog()

        Catch ex As Exception
            MessageBox.Show("ActionPrint:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            Me.Cursor = Cursors.Default
            Frm = Nothing
        End Try
    End Function

    Public Function ActionSave() As Boolean Implements IDServer.IDServer.IDServer.ActionSave
        Dim bool As Boolean = Me.btnSaveData()
        Return bool
    End Function

    Public Function ActionSelect() As Boolean Implements IDServer.IDServer.IDServer.ActionSelect
        Try
            btnFind_Click(Nothing, Nothing)
        Catch ex As Exception
            MessageBox.Show("ActionSelect:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Function

    ''' <summary>
    ''' 審核過成
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ActionChecked() As Boolean
        Try
            If CheckEnable = False Then
                MessageBox.Show("對不起，您沒有審核權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If

            Dim TabIndex As Integer = Me.TabControl1.SelectedIndex
            If TabIndex = 0 Then
                If Me.DGView_1_1.CurrentRow Is Nothing Then Return False

                Dim fDeliverId As String = Me.DGView_1_1.CurrentRow.Cells("fDeliverId").Value.ToString.Trim & ""

                Dim MasterDtab As DataTable = DirectCast(Me.DGView_1_1.DataSource, DataTable)

                Dim Sql As String = ""

                Sql &= " select * from dbo.DeliverGoodsDetail where fDeliverId='" & fDeliverId & "' and Isnull(fStatus,0)=0" & vbCrLf
                Sql &= " select a.fDeliverId,a.fSaleOrdeNo,b.fWriteNo,b.ShopNo,OutStoreHouse,fDSIA,fDSIB,fBSI  from dbo.DeliverGoodsDetail a inner join dbo.Sal_SaleOrdeA b on (a.fSaleOrdeNo=b.fSaleOrdeNo)  where  a.fDeliverId='" & fDeliverId & "' " & vbCrLf
                Dim Dset As New DataSet

                Dset = Exec(Sql, E_ExecType.DataSet)
                If Dset.Tables(0).Rows.Count > 0 Then
                    MessageBox.Show("存在沒有處理的預排單。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Return False
                End If

                Dim fCheckMan As String = PubUserName
                Dim fCheckDate As String = ServerDate
                Dim fCheckComputer As String = My.Computer.Name

                Dim TextValue As New System.Text.StringBuilder

                Sql = "  Update dbo.DeliverGoodsMaster set Status='B',fCheckMan='" & fCheckMan & "',fCheckDate=getdate(),fCheckComputer='" & fCheckComputer & "' where fDeliverId='" & fDeliverId & "' " & vbCrLf

                Dim Union As String = " Union " & vbCrLf
                Dim I As Integer = 0

                For Each Row As DataRow In Dset.Tables(1).Rows

                    Dim TextStr As String = ""

                    If I = 0 Then
                        TextStr &= " Declare  @FNum varchar(50)" & vbCrLf
                        TextStr &= " Declare  @FTAmount Decimal(18,2)--送貨總金額" & vbCrLf
                        TextStr &= " Declare  @FDSIA Decimal(18,2)--實收金額" & vbCrLf
                        TextStr &= " Declare  @FDSIB Decimal(18,2)--應付金額/(FBSI)尾數" & vbCrLf
                        TextStr &= " Declare  @FValue varchar(10) --計算累計已收時是否只統計已審核的單據" & vbCrLf
                        TextStr &= " Declare  @FPayInFull Int " & vbCrLf
                        TextStr &= " Declare  @FBSI decimal(18,2)" & vbCrLf
                    End If

                    Dim ShopNo As String = Row("ShopNo") & ""
                    Dim FSaleOrdeNo As String = Row("FSaleOrdeNo") & ""
                    Dim FWriteNo As String = Row("FWriteNo") & ""

                    'TextStr &= "  select @FValue=FValue from BSC_SystemProfile where FCategory='AR' and FKey='NeedCheck' " & vbCrLf

                    ''TextStr &= "  select @FTAmount=Isnull(Sum(fSumMoney),0) from DeliverGoodsInfo where Isnull(fDeliverId,'')='" & fDeliverId & "' and Isnull(fSaleOrdeNo,'')='" & FSaleOrdeNo & "' " & vbCrLf
                    ''TextStr &= "  set @FDSIA=0" & vbCrLf
                    ''TextStr &= "  select @FDSIB=FBSI from  Sal_SaleOrdeA where Isnull(fSaleOrdeNo,'')='" & FSaleOrdeNo & "'" & vbCrLf
                    ''TextStr &= "  if @FValue='Y'" & vbCrLf
                    ''TextStr &= "    Begin" & vbCrLf
                    ''TextStr &= "        select @FDSIB=@FDSIB-Isnull(Sum(FReceipt),0) from Sal_InvoiceA where Isnull(fSaleOrdeNo,'')='" & FSaleOrdeNo & "' and FType='BALANCE'  and Isnull(BillStatusId,'')='B'" & vbCrLf
                    ''TextStr &= "    End" & vbCrLf
                    ''TextStr &= "  Else" & vbCrLf
                    ''TextStr &= "    Begin" & vbCrLf
                    ''TextStr &= "        select @FDSIB=@FDSIB-Isnull(Sum(FReceipt),0) from Sal_InvoiceA where Isnull(fSaleOrdeNo,'')='" & FSaleOrdeNo & "' and FType='BALANCE'  and Isnull(BillStatusId,'') not in ('D','E') " & vbCrLf
                    ''TextStr &= "    End" & vbCrLf

                    ''TextStr &= "   select  @FNum=dbo.ReturnInvNo('" & FSaleOrdeNo & "')" & vbCrLf

                    ' ''尾數計算方法
                    ' ''1)是否已全數付清  尾數為0
                    ' ''2)部份付清        應收-累計已收

                    'TextStr &= "set @FBSI=0.00"

                    'TextStr &= " if @FValue='Y'"
                    'TextStr &= "    Begin"
                    'TextStr &= "    if @FPayInFull<>1"
                    'TextStr &= "        Begin"
                    'TextStr &= "            select  @FBSI=(select Isnull(Sum(fSumMoney),0) from dbo.Sal_SaleOrdeB where fSaleordeNo='" & FSaleOrdeNo & "')"
                    'TextStr &= "            -(select Isnull(Sum(FDSIA),0) from Sal_InvoiceA  where fSaleordeNo='" & FSaleOrdeNo & "' and fType='DEPOSIT' and BillStatusId in ('B','F'))"
                    'TextStr &= "            -(select Isnull(Sum(FReceipt),0) from Sal_InvoiceA  where fSaleordeNo='" & FSaleOrdeNo & "' and fType='BALANCE'  and BillStatusId in ('B','F'))"
                    'TextStr &= "        End"
                    'TextStr &= "    End"
                    'TextStr &= " Else"
                    'TextStr &= "    Begin"
                    'TextStr &= "    if @FPayInFull<>1"
                    'TextStr &= "        Begin"
                    'TextStr &= "            select  @FBSI=(select Isnull(Sum(fSumMoney),0) from dbo.Sal_SaleOrdeB where fSaleordeNo='" & FSaleOrdeNo & "')"
                    'TextStr &= "            -(select Isnull(Sum(FDSIA),0) from Sal_InvoiceA  where fSaleordeNo='" & FSaleOrdeNo & "' and fType='DEPOSIT'  and BillStatusId not in ('D','E'))"
                    'TextStr &= "            -(select Isnull(Sum(FReceipt),0) from Sal_InvoiceA  where fSaleordeNo='" & FSaleOrdeNo & "' and fType='BALANCE'  and BillStatusId not in ('D','E'))"
                    'TextStr &= "        End"
                    'TextStr &= "    End"


                    'TextStr &= "  select  @FNum=dbo.getMaxNum('SalInvoice')" & vbCrLf

                    'TextStr &= "  Insert Into Sal_InvoiceA(FNum,FDate,ShopNo,FSaleOrdeNo,FDeliverId,FWriteNo,FType,BulidBy,BulidDate,BulidComputer,BillStatusId,FDSIA,FDSIB,FBSI,FTAmount)" & vbCrLf
                    'TextStr &= "  values(@FNum,'" & fCheckDate & "','" & ShopNo & "','" & FSaleOrdeNo & "','" & fDeliverId & "','" & FWriteNo & "','BALANCE','" & fCheckMan & "','" & fCheckDate & "','" & fCheckComputer & "','A',0.00,@FBSI,0,@FBSI)" & vbCrLf & vbCrLf

                    'TextStr &= "  Update DeliverGoodsDetail set FNum=@FNum where Isnull(fDeliverId,'')='" & fDeliverId & "' and Isnull(fSaleOrdeNo,'')='" & FSaleOrdeNo & "'" & vbCrLf
                    'TextStr &= "  Update Number set Number=Replace(@FNum,'INV','')  where BillType='SalInvoice' " & vbCrLf

                    TextStr &= PerpareCommandInv(ShopNo, FSaleOrdeNo, FWriteNo, fCheckDate, fDeliverId, fCheckMan, fCheckComputer)

                    TextValue.Append(TextStr)

                    I += 1
                Next

                Sql &= "  Update DeliverGoodsDetail set BillStatus='B' where Isnull(fDeliverId,'')='" & fDeliverId & "'  " & vbCrLf

                If TextValue.ToString.Trim <> "" Then
                    Sql &= TextValue.ToString.Trim
                End If
                Exec(Sql, E_ExecType.ExecuteNonQuery, True)

                Dim DRow() As DataRow = MasterDtab.Select("fDeliverId='" & fDeliverId & "'")



                If DRow.Length > 0 Then
                    DRow(0).Item("Status") = "核准"
                    DRow(0).Item("fStatus") = "B"
                    DRow(0).Item("fCheckMan") = fCheckMan
                    DRow(0).Item("fCheckDate") = fCheckDate
                    DRow(0).Item("fCheckComputer") = fCheckComputer
                End If
                MasterDtab.AcceptChanges()

                MessageBox.Show(My.Resources.CheckSuccess, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                SetButton(ButtonType.Browse, True)
                SetDataGridViewBackColor(Me.DGView_1_1, "Status")

            Else

            End If

            Return True
        Catch ex As Exception
            MessageBox.Show("ActionChecked:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Function

    ''' <summary>
    ''' 反審核
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ActionUnchecked() As Boolean

        Try
            If UncheckEnable = False Then
                MessageBox.Show("對不起，您沒有反審核權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If

            Dim TabIndex As Integer = Me.TabControl1.SelectedIndex
            If TabIndex = 0 Then
                If Me.DGView_1_1.CurrentRow Is Nothing Then Return False
                Dim Sql As String = ""
                Dim fDeliverId As String = Me.DGView_1_1.CurrentRow.Cells("fDeliverId").Value.ToString.Trim & ""

                Dim MasterDtab As DataTable = DirectCast(Me.DGView_1_1.DataSource, DataTable)

                Dim fUnCheckMan As String = PubUserName
                Dim fUnCheckDate As String = ServerDate
                Dim fUnCheckComputer As String = My.Computer.Name

                Dim Tab As New DataTable

                Sql = "select * from V_DeliverGoods  a where Isnull(BillStatus,'') in ('E','F') and Isnull(a.fDeliverId,'')='" & fDeliverId & "'"
                Tab = Exec(Sql, E_ExecType.DataTable)
                If Tab.Rows.Count > 0 Then
                    MessageBox.Show("已送貨，不能反審核。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Warning)
                    Return False
                End If

                Dim Dtab As New DataTable

                Sql = " select a.fDeliverId,a.fSaleOrdeNo,b.fWriteNo,b.ShopNo,OutStoreHouse,fDSIA,fDSIB,fBSI  from dbo.DeliverGoodsDetail a inner join dbo.Sal_SaleOrdeA b on (a.fSaleOrdeNo=b.fSaleOrdeNo)  where  a.fDeliverId='" & fDeliverId & "' " & vbCrLf

                Dtab = Exec(Sql, E_ExecType.DataTable)

                Sql = "   Update dbo.DeliverGoodsMaster set Status='C',fCheckMan=Null,fCheckDate=Null,fCheckComputer=Null,fUnCheckMan='" & fUnCheckMan & "',fUnCheckDate=Getdate(),fUnCheckComputer='" & fUnCheckComputer & "'   where fDeliverId='" & fDeliverId & "' " & vbCrLf & vbCrLf
                Sql &= "  Update DeliverGoodsDetail set FNum=Null where Isnull(fDeliverId,'')='" & fDeliverId & "' " & vbCrLf

                For Each Row As DataRow In Dtab.Rows
                    Dim FSaleOrdeNo As String = Row("fSaleOrdeNo") & ""
                    Sql &= " Delete  Sal_InvoiceA where Isnull(FSaleOrdeNo,'')='" & FSaleOrdeNo & "' and Isnull(FDeliverId,'')='" & fDeliverId & "'" & vbCrLf
                Next

                ''設成原始單
                Sql &= "  Update DeliverGoodsDetail set BillStatus='A'  where Isnull(fDeliverId,'')='" & fDeliverId & "'  " & vbCrLf

                Exec(Sql, E_ExecType.ExecuteNonQuery)

                Dim DRow() As DataRow = MasterDtab.Select("fDeliverId='" & fDeliverId & "'")

                If DRow.Length > 0 Then
                    DRow(0).Item("Status") = "反核准"
                    DRow(0).Item("fStatus") = "C"
                    DRow(0).Item("fCheckMan") = ""
                    DRow(0).Item("fCheckDate") = ""
                    DRow(0).Item("fCheckComputer") = ""
                    DRow(0).Item("fUnCheckMan") = fUnCheckMan
                    DRow(0).Item("fUnCheckDate") = fUnCheckDate
                    DRow(0).Item("fUnCheckComputer") = fUnCheckComputer
                End If
                MasterDtab.AcceptChanges()

                MessageBox.Show(My.Resources.UnCheckSuccess, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                SetButton(ButtonType.Browse, True)

            Else

            End If
            SetDataGridViewBackColor(Me.DGView_1_1, "Status")
            'Me.DGView_1_1.Rows(Me.DGView_1_1.CurrentRow.Index).DefaultCellStyle.BackColor = Color.DeepSkyBlue
            Return True
        Catch ex As Exception
            MessageBox.Show("ActionUnchecked:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Function

    ''' <summary>
    ''' 完成
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ActionComplete() As Boolean
        Try

            Return True
        Catch ex As Exception
            MessageBox.Show("ActionComplete:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Function


#End Region

#Region "ContextMenuStrip Interface"

    ''' <summary>
    ''' 添加右鍵單擊事件
    ''' </summary>
    ''' <param name="IContexMenu"></param>
    ''' <remarks></remarks>
    Public Sub AddHandlers_IContexMenu(ByVal IContexMenu As ContextMenuStrip) Implements IContextMenuStrip.AddHandlers_IContexMenu
        Try

            For Each ICMenuItem As ToolStripMenuItem In IContexMenu.Items
                AddHandler ICMenuItem.Click, AddressOf IContextMenuItem_Click
            Next

            AddHandler IContexMenu.Opening, AddressOf ContextMenuStrip_Opening

        Catch ex As Exception
            MessageBox.Show("AddHandlers_IContexMenu:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' 設置右鍵狀態
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub ContextMenuEnabled() Implements IContextMenuStrip.ContextMenuEnabled
        Dim fStatusBool As Boolean = False
        Dim fStatus As String = ""

        If Not Me.DGView_1_1.CurrentRow Is Nothing Then
            fStatus = Me.DGView_1_1.CurrentRow.Cells("fStatus").Value & ""
            If fStatus.ToLower = "B".ToLower Then
                fStatusBool = True
            End If
        End If
        Dim RowCount As Integer = Me.DGView_2_1.SelectedRows.Count
        If fStatusBool = True Then

            Dim CheckBool As Boolean = True
            Dim UnCheckBool As Boolean = True
            Dim CompleteBool As Boolean = True
            Dim DisposeBool As Boolean = True

            ''BillStatus
            For I As Integer = 0 To Me.DGView_2_1.SelectedRows.Count - 1
                Dim BillStatus As String = Me.DGView_2_1.SelectedRows(I).Cells("BillStatus").Value & ""
                Select Case BillStatus.ToUpper

                    Case "A", "" ''原始單

                        CompleteBool = False
                        DisposeBool = False
                        UnCheckBool = False

                    Case "B" ''審核
                        CheckBool = False
                    Case "C" ''反審核

                        CompleteBool = False
                        DisposeBool = False
                        UnCheckBool = False

                    Case "D", "E" ''作廢

                        CheckBool = False
                        CompleteBool = False
                        DisposeBool = False
                        UnCheckBool = False

                    Case "F" ''結案

                        CheckBool = False
                        CompleteBool = False
                        DisposeBool = False
                        UnCheckBool = False

                End Select
            Next


            Me.ToolMenu_PrintInv.Enabled = True AndAlso RowCount > 0 AndAlso (CheckBool = False OrElse CompleteBool = True)
            Me.ToolMenu_Check.Enabled = RowCount > 0 AndAlso CheckBool = True
            Me.ToolMenu_UnCheck.Enabled = RowCount > 0 AndAlso UnCheckBool = True
            Me.ToolMenu_Complete.Enabled = RowCount > 0 AndAlso CompleteBool = True
            Me.ToolMenu_Dispose.Enabled = RowCount > 0 AndAlso DisposeBool = True

        Else
            For Each ICMenuItem As ToolStripMenuItem In Me.ContextMenuStrip1.Items
                ICMenuItem.Enabled = False
            Next
        End If

    End Sub

    ''' <summary>
    ''' 右鍵打開的時侯
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Public Sub ContextMenuStrip_Opening(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Implements IContextMenuStrip.ContextMenuStrip_Opening
        ContextMenuEnabled()
    End Sub

    ''' <summary>
    ''' 右鍵單擊事件
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Public Sub IContextMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Implements IContextMenuStrip.IContextMenuItem_Click
        Try
            Dim ICMenuItem As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)

            Select Case ICMenuItem.Name.ToLower

                Case Me.ToolMenu_PrintInv.Name.ToLower ''打印尾數發票

                    ToolMenu_PrintInv_Click()

                Case Me.ToolMenu_Check.Name.ToLower ''審核

                    ToolMenu_Check_Click()

                Case Me.ToolMenu_UnCheck.Name.ToLower '' 反審核

                    ToolMenu_UnCheck_Click()

                Case Me.ToolMenu_Complete.Name.ToLower ''完成

                    ToolMenu_Complete_Click()

                Case Me.ToolMenu_Dispose.Name.ToLower ''報廢

                    ToolMenu_Dispose_Click()

            End Select

        Catch ex As Exception
            MessageBox.Show("IContextMenuItem_Click:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

#End Region

#Region "ContexMenuStrip Methods"

    ''' <summary>
    ''' 列印單張尾數發票
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ToolMenu_PrintInv_Click()
        Dim Frm As New Frm_Wating
        Frm.Show()
        Try

            Dim sql As String = ""

            Dim TextKey As New System.Text.StringBuilder

            For I As Integer = 0 To Me.DGView_2_1.SelectedRows.Count - 1
                If TextKey.ToString.Trim <> "" Then
                    TextKey.Append(",")
                End If
                TextKey.Append(Me.DGView_2_1.SelectedRows(I).Cells("FNum").Value & "")
            Next


            sql &= " Exec Print_InvBALANCEB '','" & TextKey.ToString.Trim & "'" & vbCrLf

            Dim Dtab As DataTable = Exec(sql, E_ExecType.DataTable)

            Dim IntRow As Integer = 10
            Dim FileName As String = ""
            FileName = GetReportPath("Delievry", "Print_InvBALANCE.rpt")
            If System.IO.File.Exists(FileName) = False Then
                MessageBox.Show("報表文件不存在!", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit Sub
            End If

            Dim MyRepDoc As New CrystalDecisions.CrystalReports.Engine.ReportDocument

            MyRepDoc.Load(FileName)

            SetCrystalReportLoginfo(MyRepDoc)

            MyRepDoc.SetDataSource(Dtab)
            My.Forms.Frm_Report.CrystalReportViewer1.ReportSource = MyRepDoc
            My.Forms.Frm_Report.CrystalReportViewer1.RefreshReport()
            My.Forms.Frm_Report.CrystalReportViewer1.DisplayGroupTree = False
            Frm.Dispose()
            Frm_Report.ShowDialog()

        Catch ex As Exception
            MessageBox.Show("btnPrintInv_Click:" & ex.Message)
        Finally
            Frm = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' 審核
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ToolMenu_Check_Click()

        Dim sql As String = ""
        Dim fDeliverId As String = Me.txtfDeliverId.Text.Trim & ""
        Dim TextKey As New System.Text.StringBuilder

        Dim fCheckMan As String = PubUserName
        Dim fCheckDate As String = ServerDate
        Dim fCheckComputer As String = My.Computer.Name
        Dim Dtab As New DataTable
        Dtab = DirectCast(Me.DGView_2_1.DataSource, DataTable)

        Dim TextValue As New System.Text.StringBuilder


        For I As Integer = 0 To Me.DGView_2_1.SelectedRows.Count - 1
            Dim TextStr As String = ""

            If I = 0 Then
                TextStr &= " Declare  @FNum varchar(50)" & vbCrLf
                TextStr &= " Declare  @FTAmount Decimal(18,2)--送貨總金額" & vbCrLf
                TextStr &= " Declare  @FDSIA Decimal(18,2)--實收金額" & vbCrLf
                TextStr &= " Declare  @FDSIB Decimal(18,2)--應付金額/(FBSI)尾數" & vbCrLf
                TextStr &= " Declare  @FValue varchar(10) --計算累計已收時是否只統計已審核的單據" & vbCrLf
                TextStr &= " Declare  @FPayInFull Int " & vbCrLf
                TextStr &= " Declare  @FBSI decimal(18,2)" & vbCrLf
            End If

            Dim ShopNo As String = Me.DGView_2_1.SelectedRows(I).Cells("ShopNo").Value & ""
            Dim FSaleOrdeNo As String = Me.DGView_2_1.SelectedRows(I).Cells("FSaleOrdeNo").Value & ""
            Dim FWriteNo As String = Me.DGView_2_1.SelectedRows(I).Cells("FWriteNo").Value & ""

            If TextKey.ToString.Trim <> "" Then
                TextKey.Append(",")
            End If
            TextKey.Append("'")
            TextKey.Append(FSaleOrdeNo)
            TextKey.Append("'")

            TextStr &= PerpareCommandInv(ShopNo, FSaleOrdeNo, FWriteNo, fCheckDate, fDeliverId, fCheckMan, fCheckComputer)

            TextValue.Append(TextStr)

            I += 1
        Next

        sql &= TextValue.ToString.Trim & vbCrLf

        sql &= "  Update DeliverGoodsDetail set BillStatus='B'  where Isnull(fDeliverId,'')='" & fDeliverId & "'  and Isnull(FSaleOrdeNo,'') in (" & TextKey.ToString.Trim & ")" & vbCrLf

        Try

            Exec(sql, E_ExecType.ExecuteNonQuery)

            Dim DRow() As DataRow = Dtab.Select("fDeliverId='" & fDeliverId & "' and fSaleOrdeNo in (" & TextKey.ToString.Trim & ")")

            For Each Row As DataRow In DRow
                Row("BillStatus") = "B"
            Next

            Dtab.AcceptChanges()

            MessageBox.Show("操作成功。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)

        Catch ex As Exception
            MessageBox.Show("操作失敗:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

    End Sub

    ''' <summary>
    ''' 反審核
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ToolMenu_UnCheck_Click()

        Dim sql As String = ""
        Dim fDeliverId As String = Me.txtfDeliverId.Text.Trim & ""
        Dim TextKey As New System.Text.StringBuilder

        Dim Dtab As New DataTable
        Dtab = DirectCast(Me.DGView_2_1.DataSource, DataTable)


        For I As Integer = 0 To Me.DGView_2_1.SelectedRows.Count - 1
            If TextKey.ToString.Trim <> "" Then
                TextKey.Append(",")
            End If
            TextKey.Append("'")
            TextKey.Append(Me.DGView_2_1.SelectedRows(I).Cells("fSaleOrdeNo").Value & "")
            TextKey.Append("'")
        Next

        sql &= " Delete  Sal_InvoiceA where Isnull(FSaleOrdeNo,'') in (" & TextKey.ToString.Trim & ") and Isnull(FDeliverId,'')='" & fDeliverId & "'" & vbCrLf

        ''設成原始單
        sql &= "  Update DeliverGoodsDetail set BillStatus='A'  where Isnull(fDeliverId,'')='" & fDeliverId & "'  and Isnull(FSaleOrdeNo,'') in (" & TextKey.ToString.Trim & ")" & vbCrLf

        Try

            Exec(sql, E_ExecType.ExecuteNonQuery)

            Dim DRow() As DataRow = Dtab.Select("fDeliverId='" & fDeliverId & "' and fSaleOrdeNo in (" & TextKey.ToString.Trim & ")")

            For Each Row As DataRow In DRow
                Row("BillStatus") = "A"
            Next

            Dtab.AcceptChanges()

            MessageBox.Show("操作成功。", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)

        Catch ex As Exception
            MessageBox.Show("操作失敗:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

    End Sub

    ''' <summary>
    ''' 完成
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ToolMenu_Complete_Click()
        Try

            If MessageBox.Show("確定送貨已完成？", Msg.CompanyName, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) <> DialogResult.OK Then Exit Sub

            Dim sql As String = ""
            Dim fDeliverId As String = txtfDeliverId.Text.Trim
            Dim fSaleOrdeNo As String = ""

            Dim TextKey As New System.Text.StringBuilder
            Dim Dtab As New DataTable
            Dtab = DirectCast(Me.DGView_2_1.DataSource, DataTable)


            For I As Integer = 0 To Me.DGView_2_1.SelectedRows.Count - 1
                If TextKey.ToString.Trim <> "" Then
                    TextKey.Append(",")
                End If
                TextKey.Append("'")
                TextKey.Append(Me.DGView_2_1.SelectedRows(I).Cells("fSaleOrdeNo").Value & "")
                TextKey.Append("'")
            Next

            sql &= " update DeliverGoodsDetail set BillStatus='F',confirmdate=Convert(nvarchar(19),Getdate(),21)  where fDeliverId='" & fDeliverId & "' and  fSaleOrdeNo in (" & TextKey.ToString.Trim & ")" & vbCrLf

            Exec(sql, E_ExecType.ExecuteNonQuery)

            Dim DRow() As DataRow = Dtab.Select("fDeliverId='" & fDeliverId & "' and fSaleOrdeNo in (" & TextKey.ToString.Trim & ")")

            For Each Row As DataRow In DRow
                Row("BillStatus") = "F"
            Next
            Dtab.AcceptChanges()
            MessageBox.Show("操作成功！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        Catch ex As Exception
            MessageBox.Show("操作失敗！" & ex.Message, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub


    ''' <summary>
    ''' 重新安排送貨
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ToolMenu_Dispose_Click()
        Try
            If MessageBox.Show("確定要重新安排送貨？", Msg.CompanyName, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) <> DialogResult.OK Then Exit Sub

            Dim sql As String = ""
            Dim fDeliverId As String = Me.txtfDeliverId.Text.Trim
            Dim fSaleOrdeNo As String = ""

            Dim TextKey As New System.Text.StringBuilder
            Dim Dtab As New DataTable
            Dtab = DirectCast(Me.DGView_2_1.DataSource, DataTable)


            For I As Integer = 0 To Me.DGView_2_1.SelectedRows.Count - 1
                If TextKey.ToString.Trim <> "" Then
                    TextKey.Append(",")
                End If
                TextKey.Append("'")
                TextKey.Append(Me.DGView_2_1.SelectedRows(I).Cells("fSaleOrdeNo").Value & "")
                TextKey.Append("'")
            Next

            sql &= " update DeliverGoodsDetail set BillStatus='E',confirmdate=Convert(nvarchar(19),Getdate(),21)  where fDeliverId='" & fDeliverId & "' and  fSaleOrdeNo in (" & TextKey.ToString.Trim & ")" & vbCrLf

            Exec(sql, E_ExecType.ExecuteNonQuery)

            Dim DRow() As DataRow = Dtab.Select("fDeliverId='" & fDeliverId & "' and fSaleOrdeNo in (" & TextKey.ToString.Trim & ")")

            For Each Row As DataRow In DRow
                Row("BillStatus") = "E"
            Next

            Dtab.AcceptChanges()
            MessageBox.Show("操作成功！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        Catch ex As Exception
            MessageBox.Show("操作失敗！" & ex.Message, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    'Private Function OperateFactoryMeunItem(ByVal Index As Integer)

    'End Function

#End Region


End Class
